lapis
lapis copied to clipboard
When I have two mysql data sources or Multiple data source,how to use lapis
When I have two mysql data sources or Multiple data source,how to use lapis
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.
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 ?
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
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.
I've done it! This is how I did:
- First I've copied
lapis/db/mysql.luato my website folder inlib/mdb.lua. - Then I've patched it to support different mysql configurations as an argument to use with
requireit, you can see the patch at https://gist.github.com/edubart/b08266fd44395c0d99a3bf464547b3f3/revisions - Then I've added a new mysql configuration in
config.luacalledmysql2. - Now in my project where I need de second database connection I use
mdbjust like I would uselapis.db:
local mdb = require('lib.mdb')('mysql2')
- To use models, just set the
dbfield tomdb, 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 thks, i try it this good idea
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"