lapis icon indicating copy to clipboard operation
lapis copied to clipboard

When I have two mysql data sources or Multiple data source,how to use lapis

Open sixtool opened this issue 6 years ago • 7 comments
trafficstars

When I have two mysql data sources or Multiple data source,how to use lapis

sixtool avatar Dec 12 '18 13:12 sixtool

There's no easy way to do this right now since lapis manages a singleton for the db object (the primary database connection). You're welcome to create your own modules for any other connections you want to have open. Are you trying to use models along with your secondary database? If so, it's possible to provide an alternate db object on the class level for models. Tell me if you need more info.

leafo avatar Dec 12 '18 22:12 leafo

Yes!, I trying to use models along the secondary database,How to use it? oh, I can only create my own module to connection database ?

sixtool avatar Dec 13 '18 11:12 sixtool

local config = require("lapis.config").get() if config.postgres then return require("lapis.db.postgres") elseif config.mysql then return require("lapis.db.mysql") elseif config.masql2 then -- like this? return require("lapis.db.mysql") -- else return error("You have to configure either postgres or mysql") end

sixtool avatar Dec 13 '18 11:12 sixtool

I'm also needing this. In my case I have two mysql instances on different servers, so I do need two connections using the resty_mysql backend.

edubart avatar Dec 14 '18 20:12 edubart

I've done it! This is how I did:

  1. First I've copied lapis/db/mysql.lua to my website folder in lib/mdb.lua.
  2. Then I've patched it to support different mysql configurations as an argument to use with require it, you can see the patch at https://gist.github.com/edubart/b08266fd44395c0d99a3bf464547b3f3/revisions
  3. Then I've added a new mysql configuration in config.lua called mysql2.
  4. Now in my project where I need de second database connection I use mdb just like I would use lapis.db:
local mdb = require('lib.mdb')('mysql2')
  1. To use models, just set the db field to mdb, for example:
local User = Model:extend("users")
User.db = require('lib.mdb')('mysql2')

The patch is simple, maybe @leafo could incorporate something like this in the project in the future supporting other drivers too, I've tried doing a PR for this but failed because I'm not used Moonscript syntax and would require more changes on the other drivers too.

edubart avatar Dec 14 '18 22:12 edubart

@edubart thks, i try it this good idea

sixtool avatar Dec 21 '18 10:12 sixtool

laefo, any update on a good approach for this with the latest version? I personally think, being able to provide the connection options from within the model would be a good approach. Is that what you meant by "provide an alternate db object on the class level for models"

emadsamir avatar Jan 01 '21 23:01 emadsamir