gosora/query_gen/mssql.go

1236 lines
40 KiB
Go
Raw Normal View History

/* WIP Under Really Heavy Construction */
package qgen
import (
2022-02-21 03:53:13 +00:00
"database/sql"
"errors"
"log"
"strconv"
"strings"
)
func init() {
2022-02-21 03:32:53 +00:00
Registry = append(Registry,
&MssqlAdapter{Name: "mssql", Buffer: make(map[string]DBStmt)},
)
}
type MssqlAdapter struct {
2022-02-21 03:32:53 +00:00
Name string // ? - Do we really need this? Can't we hard-code this?
Buffer map[string]DBStmt
BufferOrder []string // Map iteration order is random, so we need this to track the order, so we don't get huge diffs every commit
keys map[string]string
}
// GetName gives you the name of the database adapter. In this case, it's Mssql
func (a *MssqlAdapter) GetName() string {
2022-02-21 03:32:53 +00:00
return a.Name
}
func (a *MssqlAdapter) GetStmt(name string) DBStmt {
2022-02-21 03:32:53 +00:00
return a.Buffer[name]
}
func (a *MssqlAdapter) GetStmts() map[string]DBStmt {
2022-02-21 03:32:53 +00:00
return a.Buffer
}
Fixed a bug where it would use the wrong templates for Tempra Simple, Tempra Cursive, and Shadow Likes are now done over AJAX. Posts you have liked are now visually differentiated from those which you have not. Added support for OR to the where parser. || and && now get translated to OR and AND in the where parser. Added support for ( and ) in the where parser. Added an adapter and builder method for getting the database version. Multiple wheres can now be chained with the micro and accumulator builders. Added the In method to the accumulator select builder. Added the GetConn method to the builder. /uploads/ files should now get cached properly. Added more tooltips for topic titles and usernames. Fixed a bug in the runners where old stale templates would be served. Fixed a bug where liking topics didn't work. Began moving the database initialisation logic out of {adapter}.go and into querygen. Tweaked the alert direction to show the newest alerts rather than the oldest. Tweaked the WS JS to have it handle messages more efficiently. Partially fixed an issue where inline edited posts would lack newlines until the page is refreshed. Used arrow functions in a few places in global.js to save a few characters. Schema: Added the liked, oldestItemLikedCreatedAt and lastLiked columns to the users table. Added the createdAt column to the likes table. MySQL Update Queries: ALTER TABLE `users` ADD COLUMN `liked` INT NOT NULL DEFAULT '0' AFTER `topics`; ALTER TABLE `users` ADD COLUMN `oldestItemLikedCreatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `liked`; ALTER TABLE `users` ADD COLUMN `lastLiked` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `oldestItemLikedCreatedAt`; ALTER TABLE `likes` ADD COLUMN `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `sentBy`; delete from `likes`; delete from `activity_stream` where `event` = 'like'; delete from `activity_stream_matches` where `asid` not in(select `asid` from `activity_stream`); update `topics` set `likeCount` = 0; update `replies` set `likeCount` = 0;
2018-03-31 05:25:27 +00:00
// TODO: Implement this
func (a *MssqlAdapter) BuildConn(config map[string]string) (*sql.DB, error) {
2022-02-21 03:32:53 +00:00
return nil, nil
Fixed a bug where it would use the wrong templates for Tempra Simple, Tempra Cursive, and Shadow Likes are now done over AJAX. Posts you have liked are now visually differentiated from those which you have not. Added support for OR to the where parser. || and && now get translated to OR and AND in the where parser. Added support for ( and ) in the where parser. Added an adapter and builder method for getting the database version. Multiple wheres can now be chained with the micro and accumulator builders. Added the In method to the accumulator select builder. Added the GetConn method to the builder. /uploads/ files should now get cached properly. Added more tooltips for topic titles and usernames. Fixed a bug in the runners where old stale templates would be served. Fixed a bug where liking topics didn't work. Began moving the database initialisation logic out of {adapter}.go and into querygen. Tweaked the alert direction to show the newest alerts rather than the oldest. Tweaked the WS JS to have it handle messages more efficiently. Partially fixed an issue where inline edited posts would lack newlines until the page is refreshed. Used arrow functions in a few places in global.js to save a few characters. Schema: Added the liked, oldestItemLikedCreatedAt and lastLiked columns to the users table. Added the createdAt column to the likes table. MySQL Update Queries: ALTER TABLE `users` ADD COLUMN `liked` INT NOT NULL DEFAULT '0' AFTER `topics`; ALTER TABLE `users` ADD COLUMN `oldestItemLikedCreatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `liked`; ALTER TABLE `users` ADD COLUMN `lastLiked` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `oldestItemLikedCreatedAt`; ALTER TABLE `likes` ADD COLUMN `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `sentBy`; delete from `likes`; delete from `activity_stream` where `event` = 'like'; delete from `activity_stream_matches` where `asid` not in(select `asid` from `activity_stream`); update `topics` set `likeCount` = 0; update `replies` set `likeCount` = 0;
2018-03-31 05:25:27 +00:00
}
func (a *MssqlAdapter) DbVersion() string {
2022-02-21 03:32:53 +00:00
return "SELECT CONCAT(SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition'))"
Fixed a bug where it would use the wrong templates for Tempra Simple, Tempra Cursive, and Shadow Likes are now done over AJAX. Posts you have liked are now visually differentiated from those which you have not. Added support for OR to the where parser. || and && now get translated to OR and AND in the where parser. Added support for ( and ) in the where parser. Added an adapter and builder method for getting the database version. Multiple wheres can now be chained with the micro and accumulator builders. Added the In method to the accumulator select builder. Added the GetConn method to the builder. /uploads/ files should now get cached properly. Added more tooltips for topic titles and usernames. Fixed a bug in the runners where old stale templates would be served. Fixed a bug where liking topics didn't work. Began moving the database initialisation logic out of {adapter}.go and into querygen. Tweaked the alert direction to show the newest alerts rather than the oldest. Tweaked the WS JS to have it handle messages more efficiently. Partially fixed an issue where inline edited posts would lack newlines until the page is refreshed. Used arrow functions in a few places in global.js to save a few characters. Schema: Added the liked, oldestItemLikedCreatedAt and lastLiked columns to the users table. Added the createdAt column to the likes table. MySQL Update Queries: ALTER TABLE `users` ADD COLUMN `liked` INT NOT NULL DEFAULT '0' AFTER `topics`; ALTER TABLE `users` ADD COLUMN `oldestItemLikedCreatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `liked`; ALTER TABLE `users` ADD COLUMN `lastLiked` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `oldestItemLikedCreatedAt`; ALTER TABLE `likes` ADD COLUMN `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `sentBy`; delete from `likes`; delete from `activity_stream` where `event` = 'like'; delete from `activity_stream_matches` where `asid` not in(select `asid` from `activity_stream`); update `topics` set `likeCount` = 0; update `replies` set `likeCount` = 0;
2018-03-31 05:25:27 +00:00
}
func (a *MssqlAdapter) DropTable(name, table string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
q := "DROP TABLE IF EXISTS [" + table + "];"
a.pushStatement(name, "drop-table", q)
return q, nil
}
// TODO: Add support for foreign keys?
// TODO: Convert any remaining stringy types to nvarchar
// We may need to change the CreateTable API to better suit Mssql and the other database drivers which are coming up
func (a *MssqlAdapter) CreateTable(name, table, charset, collation string, columns []DBTableColumn, keys []DBTableKey) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if len(columns) == 0 {
return "", errors.New("You can't have a table with no columns")
}
q := "CREATE TABLE [" + table + "] ("
for _, column := range columns {
column, size, end := a.parseColumn(column)
q += "\n\t[" + column.Name + "] " + column.Type + size + end + ","
}
if len(keys) > 0 {
for _, key := range keys {
q += "\n\t" + key.Type
if key.Type != "unique" {
q += " key"
}
q += "("
for _, column := range strings.Split(key.Columns, ",") {
q += "[" + column + "],"
}
q = q[0:len(q)-1] + "),"
}
}
q = q[0:len(q)-1] + "\n);"
a.pushStatement(name, "create-table", q)
return q, nil
}
func (a *MssqlAdapter) parseColumn(column DBTableColumn) (col DBTableColumn, size string, end string) {
2022-02-21 03:32:53 +00:00
var max, createdAt bool
switch column.Type {
case "createdAt":
column.Type = "datetime"
createdAt = true
case "varchar":
column.Type = "nvarchar"
case "text":
column.Type = "nvarchar"
max = true
case "json":
column.Type = "nvarchar"
max = true
case "boolean":
column.Type = "bit"
}
if column.Size > 0 {
size = " (" + strconv.Itoa(column.Size) + ")"
}
if max {
size = " (MAX)"
}
if column.Default != "" {
end = " DEFAULT "
if createdAt {
end += "GETUTCDATE()" // TODO: Use GETUTCDATE() in updates instead of the neutral format
} else if a.stringyType(column.Type) && column.Default != "''" {
end += "'" + column.Default + "'"
} else {
end += column.Default
}
}
if !column.Null {
end += " not null"
}
// ! Not exactly the meaning of auto increment...
if column.AutoIncrement {
end += " IDENTITY"
}
return column, size, end
UNSTABLE: Began work on the Nox Theme. Removed the Tempra Cursive Theme. You can now do bulk moderation actions with Shadow. Added: Argon2 as a dependency. The EmailStore. The ReportStore. The Copy method to *Setting. The AddColumn method to the query builder and adapters. The textarea setting type. More logging to better debug issues. The GetOffset method to the UserStore. Removed: Sortable from Code Climate's Analysis. MemberCheck and memberCheck as they're obsolete now. The obsolete url_tags setting. The BcryptGeneratePasswordNoSalt function. Some redundant fields from some of the page structs. Revamped: The Control Panel Setting List and Editor. Refactored: The password hashing logic to make it more amenable to multiple hashing algorithms. The email portion of the Account Manager. The Control Panel User List. The report system. simplePanelUserCheck and simpleUserCheck to remove the duplicated logic as the two do the exact same thing. Fixed: Missing slugs in the profile links in the User Manager. A few template initialisers potentially reducing the number of odd template edge cases. Some problems with the footer. Custom selection colour not applying to images on Shadow. The avatars of the bottom row of the topic list on Conflux leaking out. Other: Moved the startTime variable into package common and exported it. Moved the password hashing logic from user.go to auth.go Split common/themes.go into common/theme.go and common/theme_list.go Replaced the SettingLabels phrase category with the more generic SettingPhrases category. Moved a load of routes, including panel ones into the routes and panel packages. Hid the notifications link from the Account Menu. Moved more inline CSS into the CSS files and made things a little more flexible here and there. Continued work on PgSQL, still a ways away. Guests now have a default avatar like everyone else. Tweaked some of the font sizes on Cosora to make the text look a little nicer. Partially implemented the theme dock override logic. Partially implemented a "symlink" like feature for theme directories. ... And a bunch of other things I might have missed. You will need to run this update script / patcher for this commit. Warning: This is an "unstable commit", therefore some things may be a little less stable than I'd like. For instance, the Shadow Theme is a little broken in this commit.
2018-05-27 09:36:35 +00:00
}
// TODO: Test this, not sure if some things work
Added the In-Progress Widget Manager UI. Added the IsoCode field to phrase files. Rewrote a good portion of the widget system logic. Added some tests for the widget system. Added the Online Users widget. Added a few sealed incomplete widgets like the Search & Filter Widget. Added the AllUsers method to WsHubImpl for Online Users. Please don't abuse it. Added the optional *DBTableKey field to AddColumn. Added the panel_analytics_time_range template to reduce the amount of duplication. Failed registrations now show up in red in the registration logs for Nox. Failed logins now show up in red in the login logs for Nox. Added basic h2 CSS to the other themes. Added .show_on_block_edit and .hide_on_block_edit to the other themes. Updated contributing. Updated a bunch of dates to 2019. Replaced tblKey{} with nil where possible. Switched out some &s for &s to reduce the number of possible bugs. Fixed a bug with selector messages where the inspector would get really jittery due to unnecessary DOM updates. Moved header.Zone and associated fields to the bottom of ViewTopic to reduce the chances of problems arising. Added the ZoneData field to *Header. Added IDs to the items in the forum list template. Split the fetchPhrases function into the initPhrases and fetchPhrases functions in init.js Added .colstack_sub_head. Fixed the CSS in the menu list. Removed an inline style from the simple topic like and unlike buttons. Removed an inline style from the simple topic IP button. Simplified the LoginRequired error handler. Fixed a typo in the comment prior to DatabaseError() Reduce the number of false leaves for WebSocket page transitions. Added the error zone. De-duped the logic in WsHubImpl.getUsers. Fixed a potential widget security issue. Added twenty new phrases. Added the wid column to the widgets table. You will need to run the patcher / updater for this commit.
2019-01-21 12:27:59 +00:00
// TODO: Add support for keys
func (a *MssqlAdapter) AddColumn(name, table string, column DBTableColumn, key *DBTableKey) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
column, size, end := a.parseColumn(column)
q := "ALTER TABLE [" + table + "] ADD [" + column.Name + "] " + column.Type + size + end + ";"
a.pushStatement(name, "add-column", q)
return q, nil
UNSTABLE: Began work on the Nox Theme. Removed the Tempra Cursive Theme. You can now do bulk moderation actions with Shadow. Added: Argon2 as a dependency. The EmailStore. The ReportStore. The Copy method to *Setting. The AddColumn method to the query builder and adapters. The textarea setting type. More logging to better debug issues. The GetOffset method to the UserStore. Removed: Sortable from Code Climate's Analysis. MemberCheck and memberCheck as they're obsolete now. The obsolete url_tags setting. The BcryptGeneratePasswordNoSalt function. Some redundant fields from some of the page structs. Revamped: The Control Panel Setting List and Editor. Refactored: The password hashing logic to make it more amenable to multiple hashing algorithms. The email portion of the Account Manager. The Control Panel User List. The report system. simplePanelUserCheck and simpleUserCheck to remove the duplicated logic as the two do the exact same thing. Fixed: Missing slugs in the profile links in the User Manager. A few template initialisers potentially reducing the number of odd template edge cases. Some problems with the footer. Custom selection colour not applying to images on Shadow. The avatars of the bottom row of the topic list on Conflux leaking out. Other: Moved the startTime variable into package common and exported it. Moved the password hashing logic from user.go to auth.go Split common/themes.go into common/theme.go and common/theme_list.go Replaced the SettingLabels phrase category with the more generic SettingPhrases category. Moved a load of routes, including panel ones into the routes and panel packages. Hid the notifications link from the Account Menu. Moved more inline CSS into the CSS files and made things a little more flexible here and there. Continued work on PgSQL, still a ways away. Guests now have a default avatar like everyone else. Tweaked some of the font sizes on Cosora to make the text look a little nicer. Partially implemented the theme dock override logic. Partially implemented a "symlink" like feature for theme directories. ... And a bunch of other things I might have missed. You will need to run this update script / patcher for this commit. Warning: This is an "unstable commit", therefore some things may be a little less stable than I'd like. For instance, the Shadow Theme is a little broken in this commit.
2018-05-27 09:36:35 +00:00
}
// TODO: Implement this
func (a *MssqlAdapter) DropColumn(name, table, colName string) (string, error) {
2022-02-21 03:32:53 +00:00
return "", errors.New("not implemented")
}
// TODO: Implement this
func (a *MssqlAdapter) RenameColumn(name, table, oldName, newName string) (string, error) {
2022-02-21 03:32:53 +00:00
return "", errors.New("not implemented")
}
// TODO: Implement this
func (a *MssqlAdapter) ChangeColumn(name, table, colName string, col DBTableColumn) (string, error) {
2022-02-21 03:32:53 +00:00
return "", errors.New("not implemented")
}
// TODO: Implement this
func (a *MssqlAdapter) SetDefaultColumn(name, table, colName, colType, defaultStr string) (string, error) {
2022-02-21 03:32:53 +00:00
if colType == "text" {
return "", errors.New("text fields cannot have default values")
}
return "", errors.New("not implemented")
}
// TODO: Implement this
// TODO: Test to make sure everything works here
func (a *MssqlAdapter) AddIndex(name, table, iname, colname string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if iname == "" {
return "", errors.New("You need a name for the index")
}
if colname == "" {
return "", errors.New("You need a name for the column")
}
return "", errors.New("not implemented")
}
Basic search now works for the Search & Filter Widget. ElasticSearch has been temporarily delayed, so I can push through this update. Added the three month time range to the analytics panes. Began work on adding new graphs to the analytics panes. Began work on the ElasticSearch adapter for the search system. Added the currently limited AddKey method to the database adapters. Expanded upon the column parsing logic in the database adapters to ease the use of InsertSelects. Added the BulkGet method to TopicCache. Added the BulkGetMap method to TopicStore. TopicStore methods should now properly retrieve lastReplyBy. Added the panel_analytics_script template to de-dupe part of the analytics logic. We plan to tidy this up further, but for now, it'll suffice. Added plugin_sendmail and plugin_hyperdrive to the continuous integration test list. Tweaked the width and heights of the textareas for the Widget Editor. Added the AddKey method to *qgen.builder Fixed a bug where using the inline forum editor would crash Gosora and wouldn't set the preset permissions for that forum properly. Added DotBot to the user agent analytics. Invisibles should be better handled when they're encountered now in user agent strings. Unknown language ISO Codes in headers now have the requests fully logged for debugging purposes. Shortened some of the pointer receiver names. Shortened some variable names. Added the dotbot phrase. Added the panel_statistics_time_range_three_months phrase. Added gopkg.in/olivere/elastic.v6 as a dependency. You will need to run the patcher or updater for this commit.
2019-02-23 06:29:19 +00:00
// TODO: Implement this
// TODO: Test to make sure everything works here
func (a *MssqlAdapter) AddKey(name, table, column string, key DBTableKey) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if column == "" {
return "", errors.New("You need a name for the column")
}
return "", errors.New("not implemented")
Basic search now works for the Search & Filter Widget. ElasticSearch has been temporarily delayed, so I can push through this update. Added the three month time range to the analytics panes. Began work on adding new graphs to the analytics panes. Began work on the ElasticSearch adapter for the search system. Added the currently limited AddKey method to the database adapters. Expanded upon the column parsing logic in the database adapters to ease the use of InsertSelects. Added the BulkGet method to TopicCache. Added the BulkGetMap method to TopicStore. TopicStore methods should now properly retrieve lastReplyBy. Added the panel_analytics_script template to de-dupe part of the analytics logic. We plan to tidy this up further, but for now, it'll suffice. Added plugin_sendmail and plugin_hyperdrive to the continuous integration test list. Tweaked the width and heights of the textareas for the Widget Editor. Added the AddKey method to *qgen.builder Fixed a bug where using the inline forum editor would crash Gosora and wouldn't set the preset permissions for that forum properly. Added DotBot to the user agent analytics. Invisibles should be better handled when they're encountered now in user agent strings. Unknown language ISO Codes in headers now have the requests fully logged for debugging purposes. Shortened some of the pointer receiver names. Shortened some variable names. Added the dotbot phrase. Added the panel_statistics_time_range_three_months phrase. Added gopkg.in/olivere/elastic.v6 as a dependency. You will need to run the patcher or updater for this commit.
2019-02-23 06:29:19 +00:00
}
// TODO: Implement this
// TODO: Test to make sure everything works here
func (a *MssqlAdapter) RemoveIndex(name, table, iname string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if iname == "" {
return "", errors.New("You need a name for the index")
}
return "", errors.New("not implemented")
}
// TODO: Implement this
// TODO: Test to make sure everything works here
func (a *MssqlAdapter) AddForeignKey(name, table, column, ftable, fcolumn string, cascade bool) (out string, e error) {
2022-02-21 03:32:53 +00:00
c := func(str string, val bool) {
if e != nil || !val {
return
}
e = errors.New("You need a " + str + " for this table")
}
c("name", table == "")
c("column", column == "")
c("ftable", ftable == "")
c("fcolumn", fcolumn == "")
if e != nil {
return "", e
}
return "", errors.New("not implemented")
}
func (a *MssqlAdapter) SimpleInsert(name, table, cols, fields string) (string, error) {
2022-02-21 03:32:53 +00:00
q, err := a.simpleBulkInsert(name, table, cols, []string{fields})
a.pushStatement(name, "insert", q)
return q, err
}
func (a *MssqlAdapter) SimpleBulkInsert(name, table, cols string, fieldSet []string) (string, error) {
2022-02-21 03:32:53 +00:00
q, err := a.simpleBulkInsert(name, table, cols, fieldSet)
a.pushStatement(name, "bulk-insert", q)
return q, err
}
func (a *MssqlAdapter) simpleBulkInsert(name, table, cols string, fieldSet []string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
q := "INSERT INTO [" + table + "] ("
if cols == "" {
q += ") VALUES ()"
a.pushStatement(name, "insert", q)
return q, nil
}
// Escape the column names, just in case we've used a reserved keyword
for _, col := range processColumns(cols) {
if col.Type == TokenFunc {
q += col.Left + ","
} else {
q += "[" + col.Left + "],"
}
}
q = q[0 : len(q)-1]
q += ") VALUES ("
for oi, fields := range fieldSet {
if oi != 0 {
q += ",("
}
for _, field := range processFields(fields) {
field.Name = strings.Replace(field.Name, "UTC_TIMESTAMP()", "GETUTCDATE()", -1)
//log.Print("field.Name ", field.Name)
nameLen := len(field.Name)
if field.Name[0] == '"' && field.Name[nameLen-1] == '"' && nameLen >= 3 {
field.Name = "'" + field.Name[1:nameLen-1] + "'"
}
if field.Name[0] == '\'' && field.Name[nameLen-1] == '\'' && nameLen >= 3 {
field.Name = "'" + strings.Replace(field.Name[1:nameLen-1], "'", "''", -1) + "'"
}
q += field.Name + ","
}
q = q[0:len(q)-1] + ")"
}
return q, nil
}
// ! DEPRECATED
func (a *MssqlAdapter) SimpleReplace(name, table, columns, fields string) (string, error) {
2022-02-21 03:32:53 +00:00
log.Print("In SimpleReplace")
key, ok := a.keys[table]
if !ok {
return "", errors.New("Unable to elide key from table '" + table + "', please use SimpleUpsert (coming soon!) instead")
}
log.Print("After the key check")
// Escape the column names, just in case we've used a reserved keyword
var keyPosition int
for _, column := range processColumns(columns) {
if column.Left == key {
continue
}
keyPosition++
}
var keyValue string
for fieldID, field := range processFields(fields) {
field.Name = strings.Replace(field.Name, "UTC_TIMESTAMP()", "GETUTCDATE()", -1)
nameLen := len(field.Name)
if field.Name[0] == '"' && field.Name[nameLen-1] == '"' && nameLen >= 3 {
field.Name = "'" + field.Name[1:nameLen-1] + "'"
}
if field.Name[0] == '\'' && field.Name[nameLen-1] == '\'' && nameLen >= 3 {
field.Name = "'" + strings.Replace(field.Name[1:nameLen-1], "'", "''", -1) + "'"
}
if keyPosition == fieldID {
keyValue = field.Name
continue
}
}
return a.SimpleUpsert(name, table, columns, fields, "key = "+keyValue)
}
func (a *MssqlAdapter) SimpleUpsert(name, table, columns, fields, where string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if len(columns) == 0 {
return "", errors.New("No columns found for SimpleInsert")
}
if len(fields) == 0 {
return "", errors.New("No input data found for SimpleInsert")
}
var fieldCount int
var fieldOutput string
q := "MERGE [" + table + "] WITH(HOLDLOCK) as t1 USING (VALUES("
parsedFields := processFields(fields)
for _, field := range parsedFields {
fieldCount++
field.Name = strings.Replace(field.Name, "UTC_TIMESTAMP()", "GETUTCDATE()", -1)
//log.Print("field.Name ", field.Name)
nameLen := len(field.Name)
if field.Name[0] == '"' && field.Name[nameLen-1] == '"' && nameLen >= 3 {
field.Name = "'" + field.Name[1:nameLen-1] + "'"
}
if field.Name[0] == '\'' && field.Name[nameLen-1] == '\'' && nameLen >= 3 {
field.Name = "'" + strings.Replace(field.Name[1:nameLen-1], "'", "''", -1) + "'"
}
fieldOutput += field.Name + ","
}
fieldOutput = fieldOutput[0 : len(fieldOutput)-1]
q += fieldOutput + ")) AS updates ("
// nolint The linter wants this to be less readable
for fieldID, _ := range parsedFields {
q += "f" + strconv.Itoa(fieldID) + ","
}
q = q[0:len(q)-1] + ") ON "
//querystr += "t1.[" + key + "] = "
// Add support for BETWEEN x.x
for _, loc := range processWhere(where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
q += " ?"
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
}
matched := " WHEN MATCHED THEN UPDATE SET "
notMatched := "WHEN NOT MATCHED THEN INSERT("
var fieldList string
// Escape the column names, just in case we've used a reserved keyword
for columnID, col := range processColumns(columns) {
fieldList += "f" + strconv.Itoa(columnID) + ","
if col.Type == TokenFunc {
matched += col.Left + " = f" + strconv.Itoa(columnID) + ","
notMatched += col.Left + ","
} else {
matched += "[" + col.Left + "] = f" + strconv.Itoa(columnID) + ","
notMatched += "[" + col.Left + "],"
}
}
matched = matched[0 : len(matched)-1]
notMatched = notMatched[0 : len(notMatched)-1]
fieldList = fieldList[0 : len(fieldList)-1]
notMatched += ") VALUES (" + fieldList + ");"
q += matched + " " + notMatched
// TODO: Run this on debug mode?
if name[0] == '_' {
log.Print(name+" query: ", q)
}
a.pushStatement(name, "upsert", q)
return q, nil
}
func (a *MssqlAdapter) SimpleUpdate(up *updatePrebuilder) (string, error) {
2022-02-21 03:32:53 +00:00
if up.table == "" {
return "", errors.New("You need a name for this table")
}
if up.set == "" {
return "", errors.New("You need to set data in this update statement")
}
q := "UPDATE [" + up.table + "] SET "
for _, item := range processSet(up.set) {
q += "[" + item.Column + "]="
for _, token := range item.Expr {
switch token.Type {
case TokenSub:
q += " ?"
case TokenFunc, TokenOp, TokenNumber, TokenOr:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += ","
}
q = q[0 : len(q)-1]
// Add support for BETWEEN x.x
if len(up.where) != 0 {
q += " WHERE"
for _, loc := range processWhere(up.where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenFunc, TokenOp, TokenNumber, TokenSub, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
a.pushStatement(up.name, "update", q)
return q, nil
}
func (a *MssqlAdapter) SimpleUpdateSelect(b *updatePrebuilder) (string, error) {
2022-02-21 03:32:53 +00:00
return "", errors.New("not implemented")
You can now manage the attachments for an opening post by hitting edit. The update system now uses the database as the source of truth for the last version rather than lastSchema.json Refactored several structs and bits of code, so we can avoid allocations for contexts where we never use a relative time. Clicking on the relative times on the topic list and the forum page should now take you to the post on the last page rather than just the last page. Added the reltime template function. Fixed some obsolete bits of code. Fixed some spelling mistakes. Fixed a bug where MaxBytesReader was capped at the maxFileSize rather than r.ContentLength. All of the client side templates should work again now. Shortened some statement names to save some horizontal space. accUpdateBuilder and SimpleUpdate now use updatePrebuilder behind the scenes to simplify things. Renamed selectItem to builder in AccSelectBuilder. Added a Total() method to accCountBuilder to reduce the amount of boilerplate used for row count queries. The "_builder" strings have been replaced with empty strings to help save memory, to make things slightly faster and to open the door to removing the query name in many contexts down the line. Added the open_edit and close_edit client hooks. Removed many query name checks. Split the attachment logic into separate functions and de-duplicated it between replies and topics. Improved the UI for editing topics in Nox. Used type aliases to reduce the amount of boilerplate in tables.go and patches.go Reduced the amount of boilerplate in the action post logic. Eliminated a map and a slice in the topic page for users who haven't given any likes. E.g. Guests. Fixed some long out-dated parts of the update instructions. Updated the update instructions to remove mention of the obsolete lastSchema.json Fixed a bug in init.js where /api/me was being loaded for guests. Added the MiniTopicGet, GlobalCount and CountInTopic methods to AttachmentStore. Added the MiniAttachment struct. Split the mod floaters out into their own template to reduce duplication. Removed a couple of redundant ParseForms. Added the common.skipUntilIfExistsOrLine function. Added the NotFoundJS and NotFoundJSQ functions. Added the lastReplyID and attachCount columns to the topics table.
2018-12-27 05:42:41 +00:00
}
func (a *MssqlAdapter) SimpleDelete(name string, table string, where string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if where == "" {
return "", errors.New("You need to specify what data you want to delete")
}
q := "DELETE FROM [" + table + "] WHERE"
// Add support for BETWEEN x.x
for _, loc := range processWhere(where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
q += " ?"
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = strings.TrimSpace(q[0 : len(q)-4])
a.pushStatement(name, "delete", q)
return q, nil
}
func (a *MssqlAdapter) ComplexDelete(b *deletePrebuilder) (string, error) {
2022-02-21 03:32:53 +00:00
return "", errors.New("not implemented")
}
// We don't want to accidentally wipe tables, so we'll have a separate method for purging tables instead
func (a *MssqlAdapter) Purge(name string, table string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
q := "DELETE FROM [" + table + "]"
a.pushStatement(name, "purge", q)
return q, nil
}
func (a *MssqlAdapter) SimpleSelect(name string, table string, columns string, where string, orderby string, limit string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
if len(columns) == 0 {
return "", errors.New("No columns found for SimpleSelect")
}
// TODO: Add this to the MySQL adapter in order to make this problem more discoverable?
if len(orderby) == 0 && limit != "" {
return "", errors.New("Orderby needs to be set to use limit on Mssql")
}
subCount := 0
q := ""
// Escape the column names, just in case we've used a reserved keyword
colslice := strings.Split(strings.TrimSpace(columns), ",")
for _, column := range colslice {
q += "[" + strings.TrimSpace(column) + "],"
}
q = q[0:len(q)-1] + " FROM [" + table + "]"
// Add support for BETWEEN x.x
if len(where) != 0 {
q += " WHERE"
for _, loc := range processWhere(where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
subCount++
q += " ?" + strconv.Itoa(subCount)
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
// MSSQL seems to convert the formats? so we'll compare it with a regular date. Do this with the other methods too?
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
// TODO: MSSQL requires ORDER BY for LIMIT
if len(orderby) != 0 {
q += " ORDER BY "
for _, column := range processOrderby(orderby) {
// TODO: We might want to escape this column
q += column.Column + " " + strings.ToUpper(column.Order) + ","
}
q = q[0 : len(q)-1]
}
if limit != "" {
limiter := processLimit(limit)
log.Printf("limiter: %+v\n", limiter)
if limiter.Offset != "" {
if limiter.Offset == "?" {
subCount++
q += " OFFSET ?" + strconv.Itoa(subCount) + " ROWS"
} else {
q += " OFFSET " + limiter.Offset + " ROWS"
}
}
// ! Does this work without an offset?
if limiter.MaxCount != "" {
if limiter.MaxCount == "?" {
subCount++
limiter.MaxCount = "?" + strconv.Itoa(subCount)
}
q += " FETCH NEXT " + limiter.MaxCount + " ROWS ONLY "
}
}
q = strings.TrimSpace("SELECT " + q)
// TODO: Run this on debug mode?
if name[0] == '_' && limit == "" {
log.Print(name+" query: ", q)
}
a.pushStatement(name, "select", q)
return q, nil
}
// TODO: ComplexSelect
func (a *MssqlAdapter) ComplexSelect(preBuilder *selectPrebuilder) (string, error) {
2022-02-21 03:32:53 +00:00
return "", nil
}
func (a *MssqlAdapter) SimpleLeftJoin(name string, table1 string, table2 string, columns string, joiners string, where string, orderby string, limit string) (string, error) {
2022-02-21 03:32:53 +00:00
if table1 == "" {
return "", errors.New("You need a name for the left table")
}
if table2 == "" {
return "", errors.New("You need a name for the right table")
}
if len(columns) == 0 {
return "", errors.New("No columns found for SimpleLeftJoin")
}
if len(joiners) == 0 {
return "", errors.New("No joiners found for SimpleLeftJoin")
}
// TODO: Add this to the MySQL adapter in order to make this problem more discoverable?
if len(orderby) == 0 && limit != "" {
return "", errors.New("Orderby needs to be set to use limit on Mssql")
}
subCount := 0
q := ""
for _, col := range processColumns(columns) {
var source, alias string
// Escape the column names, just in case we've used a reserved keyword
if col.Table != "" {
source = "[" + col.Table + "].[" + col.Left + "]"
} else if col.Type == TokenFunc {
source = col.Left
} else {
source = "[" + col.Left + "]"
}
if col.Alias != "" {
alias = " AS '" + col.Alias + "'"
}
q += source + alias + ","
}
// Remove the trailing comma
q = q[0 : len(q)-1]
q += " FROM [" + table1 + "] LEFT JOIN [" + table2 + "] ON "
for _, j := range processJoiner(joiners) {
q += "[" + j.LeftTable + "].[" + j.LeftColumn + "]" + j.Operator + "[" + j.RightTable + "].[" + j.RightColumn + "] AND "
}
// Remove the trailing AND
q = q[0 : len(q)-4]
// Add support for BETWEEN x.x
if len(where) != 0 {
q += " WHERE"
for _, loc := range processWhere(where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
subCount++
q += " ?" + strconv.Itoa(subCount)
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
halves := strings.Split(token.Contents, ".")
if len(halves) == 2 {
q += " [" + halves[0] + "].[" + halves[1] + "]"
} else {
q += " [" + token.Contents + "]"
}
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
// TODO: MSSQL requires ORDER BY for LIMIT
if len(orderby) != 0 {
q += " ORDER BY "
for _, column := range processOrderby(orderby) {
log.Print("column: ", column)
// TODO: We might want to escape this column
q += column.Column + " " + strings.ToUpper(column.Order) + ","
}
q = q[0 : len(q)-1]
} else if limit != "" {
key, ok := a.keys[table1]
if ok {
q += " ORDER BY [" + table1 + "].[" + key + "]"
}
}
if limit != "" {
limiter := processLimit(limit)
if limiter.Offset != "" {
if limiter.Offset == "?" {
subCount++
q += " OFFSET ?" + strconv.Itoa(subCount) + " ROWS"
} else {
q += " OFFSET " + limiter.Offset + " ROWS"
}
}
// ! Does this work without an offset?
if limiter.MaxCount != "" {
if limiter.MaxCount == "?" {
subCount++
limiter.MaxCount = "?" + strconv.Itoa(subCount)
}
q += " FETCH NEXT " + limiter.MaxCount + " ROWS ONLY "
}
}
q = strings.TrimSpace("SELECT " + q)
// TODO: Run this on debug mode?
if name[0] == '_' && limit == "" {
log.Print(name+" query: ", q)
}
a.pushStatement(name, "select", q)
return q, nil
}
func (a *MssqlAdapter) SimpleInnerJoin(name string, table1 string, table2 string, columns string, joiners string, where string, orderby string, limit string) (string, error) {
2022-02-21 03:32:53 +00:00
if table1 == "" {
return "", errors.New("You need a name for the left table")
}
if table2 == "" {
return "", errors.New("You need a name for the right table")
}
if len(columns) == 0 {
return "", errors.New("No columns found for SimpleInnerJoin")
}
if len(joiners) == 0 {
return "", errors.New("No joiners found for SimpleInnerJoin")
}
// TODO: Add this to the MySQL adapter in order to make this problem more discoverable?
if len(orderby) == 0 && limit != "" {
return "", errors.New("Orderby needs to be set to use limit on Mssql")
}
subCount := 0
q := ""
for _, col := range processColumns(columns) {
var source, alias string
// Escape the column names, just in case we've used a reserved keyword
if col.Table != "" {
source = "[" + col.Table + "].[" + col.Left + "]"
} else if col.Type == TokenFunc {
source = col.Left
} else {
source = "[" + col.Left + "]"
}
if col.Alias != "" {
alias = " AS '" + col.Alias + "'"
}
q += source + alias + ","
}
// Remove the trailing comma
q = q[0 : len(q)-1]
q += " FROM [" + table1 + "] INNER JOIN [" + table2 + "] ON "
for _, j := range processJoiner(joiners) {
q += "[" + j.LeftTable + "].[" + j.LeftColumn + "]" + j.Operator + "[" + j.RightTable + "].[" + j.RightColumn + "] AND "
}
// Remove the trailing AND
q = q[0 : len(q)-4]
// Add support for BETWEEN x.x
if len(where) != 0 {
q += " WHERE"
for _, loc := range processWhere(where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
subCount++
q += " ?" + strconv.Itoa(subCount)
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
halves := strings.Split(token.Contents, ".")
if len(halves) == 2 {
q += " [" + halves[0] + "].[" + halves[1] + "]"
} else {
q += " [" + token.Contents + "]"
}
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
// TODO: MSSQL requires ORDER BY for LIMIT
if len(orderby) != 0 {
q += " ORDER BY "
for _, column := range processOrderby(orderby) {
log.Print("column: ", column)
// TODO: We might want to escape this column
q += column.Column + " " + strings.ToUpper(column.Order) + ","
}
q = q[0 : len(q)-1]
} else if limit != "" {
key, ok := a.keys[table1]
if ok {
log.Print("key: ", key)
q += " ORDER BY [" + table1 + "].[" + key + "]"
}
}
if limit != "" {
limiter := processLimit(limit)
if limiter.Offset != "" {
if limiter.Offset == "?" {
subCount++
q += " OFFSET ?" + strconv.Itoa(subCount) + " ROWS"
} else {
q += " OFFSET " + limiter.Offset + " ROWS"
}
}
// ! Does this work without an offset?
if limiter.MaxCount != "" {
if limiter.MaxCount == "?" {
subCount++
limiter.MaxCount = "?" + strconv.Itoa(subCount)
}
q += " FETCH NEXT " + limiter.MaxCount + " ROWS ONLY "
}
}
q = strings.TrimSpace("SELECT " + q)
// TODO: Run this on debug mode?
if name[0] == '_' && limit == "" {
log.Print(name+" query: ", q)
}
a.pushStatement(name, "select", q)
return q, nil
}
func (a *MssqlAdapter) SimpleInsertSelect(name string, ins DBInsert, sel DBSelect) (string, error) {
2022-02-21 03:32:53 +00:00
// TODO: More errors.
// TODO: Add this to the MySQL adapter in order to make this problem more discoverable?
if len(sel.Orderby) == 0 && sel.Limit != "" {
return "", errors.New("Orderby needs to be set to use limit on Mssql")
}
/* Insert */
q := "INSERT INTO [" + ins.Table + "] ("
// Escape the column names, just in case we've used a reserved keyword
for _, col := range processColumns(ins.Columns) {
if col.Type == TokenFunc {
q += col.Left + ","
} else {
q += "[" + col.Left + "],"
}
}
q = q[0:len(q)-1] + ") SELECT "
/* Select */
subCount := 0
for _, col := range processColumns(sel.Columns) {
var source, alias string
// Escape the column names, just in case we've used a reserved keyword
if col.Type == TokenFunc || col.Type == TokenSub {
source = col.Left
} else {
source = "[" + col.Left + "]"
}
if col.Alias != "" {
alias = " AS [" + col.Alias + "]"
}
q += " " + source + alias + ","
}
q = q[0:len(q)-1] + " FROM [" + sel.Table + "] "
// Add support for BETWEEN x.x
if len(sel.Where) != 0 {
q += " WHERE"
for _, loc := range processWhere(sel.Where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
subCount++
q += " ?" + strconv.Itoa(subCount)
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
// TODO: MSSQL requires ORDER BY for LIMIT
if len(sel.Orderby) != 0 {
q += " ORDER BY "
for _, column := range processOrderby(sel.Orderby) {
// TODO: We might want to escape this column
q += column.Column + " " + strings.ToUpper(column.Order) + ","
}
q = q[0 : len(q)-1]
} else if sel.Limit != "" {
key, ok := a.keys[sel.Table]
if ok {
q += " ORDER BY [" + sel.Table + "].[" + key + "]"
}
}
if sel.Limit != "" {
limiter := processLimit(sel.Limit)
if limiter.Offset != "" {
if limiter.Offset == "?" {
subCount++
q += " OFFSET ?" + strconv.Itoa(subCount) + " ROWS"
} else {
q += " OFFSET " + limiter.Offset + " ROWS"
}
}
// ! Does this work without an offset?
if limiter.MaxCount != "" {
if limiter.MaxCount == "?" {
subCount++
limiter.MaxCount = "?" + strconv.Itoa(subCount)
}
q += " FETCH NEXT " + limiter.MaxCount + " ROWS ONLY "
}
}
q = strings.TrimSpace(q)
// TODO: Run this on debug mode?
if name[0] == '_' && sel.Limit == "" {
log.Print(name+" query: ", q)
}
a.pushStatement(name, "insert", q)
return q, nil
}
func (a *MssqlAdapter) simpleJoin(name string, ins DBInsert, sel DBJoin, joinType string) (string, error) {
2022-02-21 03:32:53 +00:00
// TODO: More errors.
// TODO: Add this to the MySQL adapter in order to make this problem more discoverable?
if len(sel.Orderby) == 0 && sel.Limit != "" {
return "", errors.New("Orderby needs to be set to use limit on Mssql")
}
/* Insert */
q := "INSERT INTO [" + ins.Table + "] ("
// Escape the column names, just in case we've used a reserved keyword
for _, col := range processColumns(ins.Columns) {
if col.Type == TokenFunc {
q += col.Left + ","
} else {
q += "[" + col.Left + "],"
}
}
q = q[0:len(q)-1] + ") SELECT "
/* Select */
subCount := 0
for _, col := range processColumns(sel.Columns) {
var source, alias string
// Escape the column names, just in case we've used a reserved keyword
if col.Table != "" {
source = "[" + col.Table + "].[" + col.Left + "]"
} else if col.Type == TokenFunc {
source = col.Left
} else {
source = "[" + col.Left + "]"
}
if col.Alias != "" {
alias = " AS '" + col.Alias + "'"
}
q += source + alias + ","
}
q = q[0 : len(q)-1]
q += " FROM [" + sel.Table1 + "] " + joinType + " JOIN [" + sel.Table2 + "] ON "
for _, j := range processJoiner(sel.Joiners) {
q += "[" + j.LeftTable + "].[" + j.LeftColumn + "] " + j.Operator + " [" + j.RightTable + "].[" + j.RightColumn + "] AND "
}
q = q[0 : len(q)-4]
// Add support for BETWEEN x.x
if len(sel.Where) != 0 {
q += " WHERE"
for _, loc := range processWhere(sel.Where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenSub:
subCount++
q += " ?" + strconv.Itoa(subCount)
case TokenFunc, TokenOp, TokenNumber, TokenOr, TokenNot, TokenLike:
// TODO: Split the function case off to speed things up
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
halves := strings.Split(token.Contents, ".")
if len(halves) == 2 {
q += " [" + halves[0] + "].[" + halves[1] + "]"
} else {
q += " [" + token.Contents + "]"
}
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
// TODO: MSSQL requires ORDER BY for LIMIT
if len(sel.Orderby) != 0 {
q += " ORDER BY "
for _, column := range processOrderby(sel.Orderby) {
log.Print("column: ", column)
// TODO: We might want to escape this column
q += column.Column + " " + strings.ToUpper(column.Order) + ","
}
q = q[0 : len(q)-1]
} else if sel.Limit != "" {
key, ok := a.keys[sel.Table1]
if ok {
q += " ORDER BY [" + sel.Table1 + "].[" + key + "]"
}
}
if sel.Limit != "" {
limiter := processLimit(sel.Limit)
if limiter.Offset != "" {
if limiter.Offset == "?" {
subCount++
q += " OFFSET ?" + strconv.Itoa(subCount) + " ROWS"
} else {
q += " OFFSET " + limiter.Offset + " ROWS"
}
}
// ! Does this work without an offset?
if limiter.MaxCount != "" {
if limiter.MaxCount == "?" {
subCount++
limiter.MaxCount = "?" + strconv.Itoa(subCount)
}
q += " FETCH NEXT " + limiter.MaxCount + " ROWS ONLY "
}
}
q = strings.TrimSpace(q)
// TODO: Run this on debug mode?
if name[0] == '_' && sel.Limit == "" {
log.Print(name+" query: ", q)
}
a.pushStatement(name, "insert", q)
return q, nil
}
func (a *MssqlAdapter) SimpleInsertLeftJoin(name string, ins DBInsert, sel DBJoin) (string, error) {
2022-02-21 03:32:53 +00:00
return a.simpleJoin(name, ins, sel, "LEFT")
}
func (a *MssqlAdapter) SimpleInsertInnerJoin(name string, ins DBInsert, sel DBJoin) (string, error) {
2022-02-21 03:32:53 +00:00
return a.simpleJoin(name, ins, sel, "INNER")
}
func (a *MssqlAdapter) SimpleCount(name, table, where, limit string) (string, error) {
2022-02-21 03:32:53 +00:00
if table == "" {
return "", errors.New("You need a name for this table")
}
q := "SELECT COUNT(*) FROM [" + table + "]"
// TODO: Add support for BETWEEN x.x
if len(where) != 0 {
q += " WHERE"
for _, loc := range processWhere(where) {
for _, token := range loc.Expr {
switch token.Type {
case TokenFunc, TokenOp, TokenNumber, TokenSub, TokenOr, TokenNot, TokenLike:
if strings.ToUpper(token.Contents) == "UTC_TIMESTAMP()" {
token.Contents = "GETUTCDATE()"
}
q += " " + token.Contents
case TokenColumn:
q += " [" + token.Contents + "]"
case TokenString:
q += " '" + token.Contents + "'"
default:
panic("This token doesn't exist o_o")
}
}
q += " AND"
}
q = q[0 : len(q)-4]
}
if limit != "" {
q += " LIMIT " + limit
}
q = strings.TrimSpace(q)
a.pushStatement(name, "select", q)
return q, nil
}
func (a *MssqlAdapter) Builder() *prebuilder {
2022-02-21 03:32:53 +00:00
return &prebuilder{a}
}
func (a *MssqlAdapter) Write() error {
2022-02-21 03:32:53 +00:00
var stmts, body string
for _, name := range a.BufferOrder {
if name == "" {
continue
}
stmt := a.Buffer[name]
// TODO: Add support for create-table? Table creation might be a little complex for Go to do outside a SQL file :(
if stmt.Type != "create-table" {
stmts += "\t" + name + " *sql.Stmt\n"
body += `
common.DebugLog("Preparing ` + name + ` statement.")
stmts.` + name + `, err = db.Prepare("` + stmt.Contents + `")
if err != nil {
log.Print("Error in ` + name + ` statement.")
log.Print("Bad Query: ","` + stmt.Contents + `")
return err
}
`
}
}
// TODO: Move these custom queries out of this file
out := `// +build mssql
// This file was generated by Gosora's Query Generator. Please try to avoid modifying this file, as it might change at any time.
package main
import "log"
import "database/sql"
2022-02-21 03:53:13 +00:00
import "git.tuxpa.in/a/gosora/common"
// nolint
type Stmts struct {
` + stmts + `
2022-02-21 03:32:53 +00:00
getActivityFeedByWatcher *sql.Stmt
getActivityCountByWatcher *sql.Stmt
2022-02-21 03:32:53 +00:00
Mocks bool
}
// nolint
func _gen_mssql() (err error) {
2022-02-21 03:32:53 +00:00
common.DebugLog("Building the generated statements")
` + body + `
2022-02-21 03:32:53 +00:00
return nil
}
`
2022-02-21 03:32:53 +00:00
return writeFile("./gen_mssql.go", out)
}
// Internal methods, not exposed in the interface
func (a *MssqlAdapter) pushStatement(name, stype, q string) {
2022-02-21 03:32:53 +00:00
if name == "" {
return
}
a.Buffer[name] = DBStmt{q, stype}
a.BufferOrder = append(a.BufferOrder, name)
}
func (a *MssqlAdapter) stringyType(ct string) bool {
2022-02-21 03:32:53 +00:00
ct = strings.ToLower(ct)
return ct == "char" || ct == "varchar" || ct == "datetime" || ct == "text" || ct == "nvarchar"
}
type SetPrimaryKeys interface {
2022-02-21 03:32:53 +00:00
SetPrimaryKeys(keys map[string]string)
}
func (a *MssqlAdapter) SetPrimaryKeys(keys map[string]string) {
2022-02-21 03:32:53 +00:00
a.keys = keys
}