Data store

Uses: Kong Gateway

Your custom plugins can interact with Kong Gateway entities in the PostgreSQL data store through classes we refer to as Data Access Objects (DAOs).

All entities in Kong Gateway, including custom entities are represented by:

  • A schema that describes which table the entity relates to in the data store, constraints on its fields such as foreign keys, non-null constraints etc. For custom entities, this is defined in daos.lua.
  • An instance of the DAO class mapping to the database currently in use. This class’s methods consume the schema and expose methods to insert, update, select, and delete entities of that type.

Both core entities from Kong Gateway and custom entities from plugins are available through kong.db.{entity-name}. For example:

local services  = kong.db.services
local routes    = kong.db.routes
local consumers = kong.db.consumers
local plugins   = kong.db.plugins

The DAO Lua API

The DAO class is responsible for the operations executed on a given table in the data store, generally mapping to an entity in Kong Gateway. All the underlying supported databases comply to the same interface, thus making the DAO compatible with all of them.

For example, you can use the following code to insert a Gateway Service and a plugin:

local inserted_service, err = kong.db.services:insert({
  name = "httpbin",
  url  = "https://httpbin.konghq.com",
})

local inserted_plugin, err = kong.db.plugins:insert({
  name    = "key-auth",
  service = inserted_service,
})

For a real-life example of the DAO being used in a plugin, see the Key-Auth plugin source code.

Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!