github.com/fragmenta/query@v1.5.3/query_test.go (about)

     1  package query
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"io/ioutil"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  	"testing"
    11  	"time"
    12  )
    13  
    14  // At present psql and mysql are tested, sqlite is disabled due to cross-compilation requirements
    15  
    16  // Pages is a simple example model for testing the query package which stores some fields in the db.
    17  // All functions prefixed with Pages here - normally the model would be in a separate function
    18  // so pages.Find(1) etc
    19  
    20  // Page model
    21  type Page struct {
    22  	ID        int64
    23  	UpdatedAt time.Time
    24  	CreatedAt time.Time
    25  
    26  	OtherField map[string]string
    27  	Title      string
    28  	Summary    string
    29  	Text       string
    30  
    31  	UnusedField int8
    32  }
    33  
    34  // Create a model object, called from actions.
    35  func (p *Page) Create(params map[string]string) (int64, error) {
    36  	params["created_at"] = TimeString(time.Now().UTC())
    37  	params["updated_at"] = TimeString(time.Now().UTC())
    38  	return PagesQuery().Insert(params)
    39  }
    40  
    41  // Update this model object, called from actions.
    42  func (p *Page) Update(params map[string]string) error {
    43  	params["updated_at"] = TimeString(time.Now().UTC())
    44  	return PagesQuery().Where("id=?", p.ID).Update(params)
    45  }
    46  
    47  // Delete this page
    48  func (p *Page) Delete() error {
    49  	return PagesQuery().Where("id=?", p.ID).Delete()
    50  }
    51  
    52  // NewWithColumns creates a new page instance and fills it with data from the database cols provided
    53  func PagesNewWithColumns(cols map[string]interface{}) *Page {
    54  
    55  	page := PagesNew()
    56  
    57  	// Normally you'd validate col values with something like the model/validate pkg
    58  	// we'll use a simple dummy function instead
    59  	page.ID = cols["id"].(int64)
    60  	if cols["created_at"] != nil {
    61  		page.CreatedAt = cols["created_at"].(time.Time)
    62  	}
    63  	if cols["updated_at"] != nil {
    64  		page.UpdatedAt = cols["updated_at"].(time.Time)
    65  	}
    66  
    67  	if cols["title"] != nil {
    68  		page.Title = cols["title"].(string)
    69  	}
    70  	if cols["summary"] != nil {
    71  		page.Summary = cols["summary"].(string)
    72  	}
    73  	if cols["text"] != nil {
    74  		page.Text = cols["text"].(string)
    75  	}
    76  
    77  	return page
    78  }
    79  
    80  // New initialises and returns a new Page
    81  func PagesNew() *Page {
    82  	page := &Page{}
    83  	return page
    84  }
    85  
    86  // Query returns a new query for pages
    87  func PagesQuery() *Query {
    88  	return New("pages", "id")
    89  }
    90  
    91  func PagesFind(ID int64) (*Page, error) {
    92  	result, err := PagesQuery().Where("id=?", ID).FirstResult()
    93  	if err != nil {
    94  		return nil, err
    95  	}
    96  	return PagesNewWithColumns(result), nil
    97  }
    98  
    99  func PagesFindAll(q *Query) ([]*Page, error) {
   100  	results, err := q.Results()
   101  	if err != nil {
   102  		return nil, err
   103  	}
   104  
   105  	var models []*Page
   106  	for _, r := range results {
   107  		m := PagesNewWithColumns(r)
   108  		models = append(models, m)
   109  	}
   110  
   111  	return models, nil
   112  }
   113  
   114  // ----------------------------------
   115  // Test Helpers
   116  // ----------------------------------
   117  
   118  var User = os.ExpandEnv("$USER")
   119  var Password = os.ExpandEnv("$QUERY_TEST_PASS") // may be blank
   120  
   121  var Format = "\n---\nFAILURE\n---\ninput:    %q\nexpected: %q\noutput:   %q"
   122  
   123  // ----------------------------------
   124  // PSQL TESTS
   125  // ----------------------------------
   126  
   127  func TestPQSetup(t *testing.T) {
   128  
   129  	fmt.Println("\n---\nTESTING POSTRGRESQL\n---")
   130  
   131  	// First execute sql
   132  	cmd := exec.Command("psql", "-dquery_test", "-f./tests/query_test_pq.sql")
   133  	stdout, _ := cmd.StdoutPipe()
   134  	stderr, _ := cmd.StderrPipe()
   135  	err := cmd.Start()
   136  	if err != nil {
   137  		t.Fatalf("DB Test Error %v", err)
   138  	}
   139  	io.Copy(os.Stdout, stdout)
   140  	io.Copy(os.Stderr, stderr)
   141  	cmd.Wait()
   142  
   143  	if err == nil {
   144  		// Open the database
   145  		options := map[string]string{
   146  			"adapter":  "postgres",
   147  			"user":     User, // Valid username required for databases
   148  			"password": Password,
   149  			"db":       "query_test",
   150  			"debug":    "true",
   151  		}
   152  
   153  		err = OpenDatabase(options)
   154  		if err != nil {
   155  			t.Fatalf("DB Error %v", err)
   156  		}
   157  
   158  		fmt.Printf("---\nQuery Testing Postgres - query_test DB setup complete as user %s\n---", User)
   159  	}
   160  
   161  }
   162  
   163  func TestPQFind(t *testing.T) {
   164  
   165  	// This should fail, as there is no such page
   166  	p, err := PagesFind(11)
   167  	if err == nil {
   168  		t.Fatalf(Format, "Find(11)", "nil", p, err)
   169  	}
   170  
   171  	// This should work
   172  	_, err = PagesFind(1)
   173  	if err != nil {
   174  		t.Fatalf(Format, "Find(1)", "Model object", err)
   175  	}
   176  
   177  }
   178  
   179  func TestPQCount(t *testing.T) {
   180  
   181  	// This should return 3
   182  	count, err := PagesQuery().Count()
   183  	if err != nil || count != 3 {
   184  		t.Fatalf(Format, "Count failed", "3", fmt.Sprintf("%d", count))
   185  	}
   186  
   187  	// This should return 2 - test limit ignored
   188  	count, err = PagesQuery().Where("id < 3").Order("id desc").Limit(100).Count()
   189  	if err != nil || count != 2 {
   190  		t.Fatalf(Format, "Count id < 3 failed", "2", fmt.Sprintf("%d", count))
   191  	}
   192  
   193  	// This should return 0
   194  	count, err = PagesQuery().Where("id > 3").Count()
   195  	if err != nil || count != 0 {
   196  		t.Fatalf(Format, "Count id > 3 failed", "0", fmt.Sprintf("%d", count))
   197  	}
   198  
   199  	// Test retrieving an array, then counting, then where
   200  	// This should work
   201  	q := PagesQuery().Where("id > ?", 1).Order("id desc")
   202  
   203  	count, err = q.Count()
   204  	if err != nil || count != 2 {
   205  		t.Fatalf(Format, "Count id > 1 failed", "2", fmt.Sprintf("%d", count), err)
   206  	}
   207  
   208  	// Reuse same query to get array after count
   209  	models, err := PagesFindAll(q)
   210  	if err != nil || len(models) != 2 {
   211  		t.Fatalf(Format, "Where Array after count", "len 2", err)
   212  	}
   213  
   214  }
   215  func TestPQWhere(t *testing.T) {
   216  
   217  	q := PagesQuery().Where("id > ?", 1)
   218  	models, err := PagesFindAll(q)
   219  	if err != nil || len(models) != 2 {
   220  		t.Fatalf(Format, "Where Array", "len 2", fmt.Sprintf("%d", len(models)))
   221  	}
   222  
   223  }
   224  
   225  func TestPQOrder(t *testing.T) {
   226  
   227  	// Look for pages in reverse order
   228  	q := PagesQuery().Where("id > 1").Order("id desc")
   229  	models, err := PagesFindAll(q)
   230  	if err != nil || len(models) == 0 {
   231  		t.Fatalf(Format, "Order test id desc", "3", fmt.Sprintf("%d", len(models)))
   232  		return
   233  	}
   234  
   235  	p := models[0]
   236  	if p.ID != 3 {
   237  		t.Fatalf(Format, "Order test id desc", "3", fmt.Sprintf("%d", p.ID))
   238  
   239  	}
   240  
   241  	// Look for pages in right order
   242  	q = PagesQuery().Where("id < ?", 10).Where("id < ?", 100).Order("id asc")
   243  	models, err = PagesFindAll(q)
   244  	if err != nil || models == nil {
   245  		t.Fatalf(Format, "Order test id asc", "1", err)
   246  	}
   247  
   248  	p = models[0]
   249  	// Check id and created at time are correct
   250  	if p.ID != 1 || time.Since(p.CreatedAt) > time.Second {
   251  		t.Fatalf(Format, "Order test id asc", "1", fmt.Sprintf("%d", p.ID))
   252  	}
   253  
   254  }
   255  
   256  func TestPQSelect(t *testing.T) {
   257  
   258  	var models []*Page
   259  	q := PagesQuery().Select("SELECT id,title from pages").Order("id asc")
   260  	models, err := PagesFindAll(q)
   261  	if err != nil || len(models) == 0 {
   262  		t.Fatalf(Format, "Select error on id,title", "id,title", err)
   263  	}
   264  	p := models[0]
   265  	// Check id and title selected, other values to be zero values
   266  	if p.ID != 1 || p.Title != "Title 1." || len(p.Text) > 0 || p.CreatedAt.Year() > 1 {
   267  		t.Fatalf(Format, "Select id,title", "id,title only", p)
   268  	}
   269  
   270  }
   271  
   272  // Some more damaging operations we execute at the end,
   273  // to avoid having to reload the db for each test
   274  
   275  func TestPQUpdateAll(t *testing.T) {
   276  
   277  	err := PagesQuery().UpdateAll(map[string]string{"title": "test me"})
   278  	if err != nil {
   279  		t.Fatalf(Format, "UPDATE ALL err", "udpate all records", err)
   280  	}
   281  
   282  	// Check we have all pages with same title
   283  	count, err := PagesQuery().Where("title=?", "test me").Count()
   284  
   285  	if err != nil || count != 3 {
   286  		t.Fatalf(Format, "Count after update all", "3", fmt.Sprintf("%d", count))
   287  	}
   288  
   289  }
   290  
   291  func TestPQUpdate(t *testing.T) {
   292  
   293  	p, err := PagesFind(3)
   294  	if err != nil {
   295  		t.Fatalf(Format, "Update could not find model err", "id-3", err)
   296  	}
   297  
   298  	// Should really test updates with several strings here
   299  	// Update each model with a different string
   300  	// This does also check if AllowedParams is working properly to clean params
   301  	err = p.Update(map[string]string{"title": "UPDATE 1"})
   302  	if err != nil {
   303  		t.Fatalf(Format, "Error after update", "updated", err)
   304  	}
   305  	// Check it is modified
   306  	p, err = PagesFind(3)
   307  
   308  	if err != nil {
   309  		t.Fatalf(Format, "Error after update 1", "updated", err)
   310  	}
   311  
   312  	// Check we have an update and the updated at time was set
   313  	if p.Title != "UPDATE 1" || time.Since(p.UpdatedAt) > time.Second {
   314  		t.Fatalf(Format, "Error after update 1 - Not updated properly", "UPDATE 1", p.Title)
   315  	}
   316  
   317  }
   318  
   319  func TestPQCreate(t *testing.T) {
   320  
   321  	params := map[string]string{
   322  		//	"id":		"",
   323  		"title":      "Test 98",
   324  		"text":       "My text",
   325  		"created_at": "REPLACE ME",
   326  		"summary":    "This is my summary",
   327  	}
   328  
   329  	// if your model is in a package, it could be pages.Create()
   330  	// For now to mock we just use an empty page
   331  	id, err := (&Page{}).Create(params)
   332  	if err != nil {
   333  		t.Fatalf(Format, "Err on create", err)
   334  	}
   335  
   336  	// Now find the page and test it
   337  	p, err := PagesFind(id)
   338  	if err != nil {
   339  		t.Fatalf(Format, "Err on create find", err)
   340  	}
   341  
   342  	if p.Title != "Test 98" {
   343  		t.Fatalf(Format, "Create page params mismatch", "Creation", p.Title)
   344  	}
   345  
   346  	// Check we have one left
   347  	count, err := PagesQuery().Count()
   348  
   349  	if err != nil || count != 4 {
   350  		t.Fatalf(Format, "Count after create", "4", fmt.Sprintf("%d", count))
   351  	}
   352  
   353  }
   354  
   355  func TestPQDelete(t *testing.T) {
   356  
   357  	p, err := PagesFind(3)
   358  	if err != nil {
   359  		t.Fatalf(Format, "Could not find model err", "id-3", err)
   360  	}
   361  
   362  	err = p.Delete()
   363  	if err != nil {
   364  		t.Fatalf(Format, "Error after delete", "deleted", err)
   365  	}
   366  
   367  	// Check it is gone and we get an error on next find
   368  	p, err = PagesFind(3)
   369  
   370  	if !strings.Contains(fmt.Sprintf("%s", err), "No results found") {
   371  		t.Fatalf(Format, "Error after delete 1", "1", err)
   372  	}
   373  
   374  }
   375  
   376  func TestPQDeleteAll(t *testing.T) {
   377  
   378  	err := PagesQuery().Where("id > 1").DeleteAll()
   379  	if err != nil {
   380  		t.Fatalf(Format, "DELETE ALL err", "delete al above 1 records", err)
   381  	}
   382  
   383  	// Check we have one left
   384  	count, err := PagesQuery().Count()
   385  
   386  	if err != nil || count != 1 {
   387  		t.Fatalf(Format, "Count after delete all above 1", "1", fmt.Sprintf("%d", count))
   388  	}
   389  
   390  }
   391  
   392  // This test takes some time, so only enable for speed testing
   393  func BenchmarkPQSpeed(t *testing.B) {
   394  
   395  	fmt.Println("\n---\nSpeed testing PSQL\n---")
   396  
   397  	for i := 0; i < 100000; i++ {
   398  		// ok  	github.com/fragmenta/query	20.238s
   399  
   400  		var models []*Page
   401  		q := PagesQuery().Select("SELECT id,title from pages").Where("id < i").Order("id asc")
   402  		models, err := PagesFindAll(q)
   403  		if err != nil && models != nil {
   404  
   405  		}
   406  
   407  		// ok  	github.com/fragmenta/query	21.680s
   408  		q = PagesQuery().Select("SELECT id,title from pages").Where("id < i").Order("id asc")
   409  		r, err := q.Results()
   410  		if err != nil && r != nil {
   411  
   412  		}
   413  
   414  	}
   415  
   416  	fmt.Println("\n---\nSpeed testing PSQL END\n---")
   417  
   418  }
   419  
   420  // NB this test must come last, any tests after this will try to use an invalid database reference
   421  func TestPQTeardown(t *testing.T) {
   422  
   423  	err := CloseDatabase()
   424  	if err != nil {
   425  		fmt.Println("Close DB ERROR ", err)
   426  	}
   427  }
   428  
   429  // ----------------------------------
   430  // MYSQL TESTS
   431  // ----------------------------------
   432  
   433  func TestMysqlSetup(t *testing.T) {
   434  
   435  	fmt.Println("\n---\nTESTING Mysql\n---")
   436  
   437  	// First execute sql
   438  
   439  	// read whole the file
   440  	bytes, err := ioutil.ReadFile("./tests/query_test_mysql.sql")
   441  	if err != nil {
   442  		t.Fatalf("MYSQL DB ERROR: %s", err)
   443  	}
   444  	s := string(bytes)
   445  
   446  	cmd := exec.Command("mysql", "-u", "root", "--init-command", s, "query_test")
   447  	stdout, _ := cmd.StdoutPipe()
   448  	stderr, _ := cmd.StderrPipe()
   449  	err = cmd.Start()
   450  	if err != nil {
   451  		t.Fatalf("MYSQL DB ERROR: %s", err)
   452  	}
   453  	io.Copy(os.Stdout, stdout)
   454  	io.Copy(os.Stderr, stderr)
   455  	cmd.Wait()
   456  
   457  	if err == nil {
   458  
   459  		// Open the database
   460  		options := map[string]string{
   461  			"adapter": "mysql",
   462  			"db":      "query_test",
   463  			"debug":   "true",
   464  		}
   465  
   466  		err = OpenDatabase(options)
   467  		if err != nil {
   468  			t.Fatalf("\n\n----\nMYSQL DB ERROR:\n%s\n----\n\n", err)
   469  		}
   470  
   471  		fmt.Println("---\nQuery Testing Mysql - DB setup complete\n---")
   472  	}
   473  
   474  }
   475  
   476  func TestMysqlFind(t *testing.T) {
   477  
   478  	// This should work
   479  	p, err := PagesFind(1)
   480  	if err != nil {
   481  		t.Fatalf(Format, "Find(1)", "Model object", p)
   482  	}
   483  
   484  	// This should fail, so we check that
   485  	p, err = PagesFind(11)
   486  	if err == nil {
   487  		t.Fatalf(Format, "Find(1)", "Model object", p)
   488  	}
   489  
   490  }
   491  
   492  func TestMysqlCount(t *testing.T) {
   493  
   494  	// This should return 3
   495  	count, err := PagesQuery().Count()
   496  	if err != nil || count != 3 {
   497  		t.Fatalf(Format, "Count failed", "3", fmt.Sprintf("%d", count))
   498  	}
   499  
   500  	// This should return 2 - test limit ignored
   501  	count, err = PagesQuery().Where("id < 3").Order("id desc").Limit(100).Count()
   502  	if err != nil || count != 2 {
   503  		t.Fatalf(Format, "Count id < 3 failed", "2", fmt.Sprintf("%d", count))
   504  	}
   505  
   506  	// This should return 0
   507  	count, err = PagesQuery().Where("id > 3").Count()
   508  	if err != nil || count != 0 {
   509  		t.Fatalf(Format, "Count id > 3 failed", "0", fmt.Sprintf("%d", count))
   510  	}
   511  
   512  	// Test retrieving an array, then counting, then where
   513  	// This should work
   514  	q := PagesQuery().Where("id > ?", 1).Order("id desc")
   515  
   516  	count, err = q.Count()
   517  	if err != nil || count != 2 {
   518  		t.Fatalf(Format, "Count id > 1 failed", "2", fmt.Sprintf("%d", count), err)
   519  	}
   520  
   521  	// Reuse same query to get array after count
   522  	var models []*Page
   523  	models, err = PagesFindAll(q)
   524  	if err != nil || len(models) != 2 {
   525  		t.Fatalf(Format, "Where Array after count", "len 2", err)
   526  	}
   527  
   528  }
   529  
   530  func TestMysqlWhere(t *testing.T) {
   531  
   532  	var models []*Page
   533  	q := PagesQuery().Where("id > ?", 1)
   534  	models, err := PagesFindAll(q)
   535  	if err != nil || len(models) != 2 {
   536  		t.Fatalf(Format, "Where Array", "len 2", fmt.Sprintf("%d", len(models)))
   537  	}
   538  
   539  }
   540  
   541  func TestMysqlOrder(t *testing.T) {
   542  
   543  	// Look for pages in reverse order
   544  	var models []*Page
   545  	q := PagesQuery().Where("id > 1").Order("id desc")
   546  	models, err := PagesFindAll(q)
   547  	if err != nil || len(models) == 0 {
   548  		t.Fatalf(Format, "Order test id desc", "3", fmt.Sprintf("%d", len(models)))
   549  		return
   550  	}
   551  
   552  	p := models[0]
   553  	if p.ID != 3 {
   554  		t.Fatalf(Format, "Order test id desc", "3", fmt.Sprintf("%d", p.ID))
   555  
   556  	}
   557  
   558  	// Look for pages in right order
   559  	q = PagesQuery().Where("id < ?", 10).Where("id < ?", 100).Order("id asc")
   560  	models, err = PagesFindAll(q)
   561  	if err != nil || models == nil {
   562  		t.Fatalf(Format, "Order test id asc", "1", err)
   563  	}
   564  
   565  	p = models[0]
   566  	if p.ID != 1 {
   567  		t.Fatalf(Format, "Order test id asc", "1", fmt.Sprintf("%d", p.ID))
   568  
   569  	}
   570  
   571  }
   572  
   573  func TestMysqlSelect(t *testing.T) {
   574  
   575  	var models []*Page
   576  	q := PagesQuery().Select("SELECT id,title from pages").Order("id asc")
   577  	models, err := PagesFindAll(q)
   578  	if err != nil || len(models) == 0 {
   579  		t.Fatalf(Format, "Select error on id,title", "id,title", err)
   580  	}
   581  	p := models[0]
   582  	if p.ID != 1 || p.Title != "Title 1." || len(p.Text) > 0 {
   583  		t.Fatalf(Format, "Select id,title", "id,title only", p)
   584  	}
   585  
   586  }
   587  
   588  func TestMysqlUpdate(t *testing.T) {
   589  
   590  	p, err := PagesFind(3)
   591  	if err != nil {
   592  		t.Fatalf(Format, "Update could not find model err", "id-3", err)
   593  	}
   594  
   595  	// Should really test updates with several strings here
   596  	// Update each model with a different string
   597  	// This does also check if AllowedParams is working properly to clean params
   598  	err = p.Update(map[string]string{"title": "UPDATE 1"})
   599  	if err != nil {
   600  		t.Fatalf(Format, "Error after update", "updated", err)
   601  	}
   602  
   603  	// Check it is modified
   604  	p, err = PagesFind(3)
   605  
   606  	if err != nil {
   607  		t.Fatalf(Format, "Error after update 1", "updated", err)
   608  	}
   609  
   610  	if p.Title != "UPDATE 1" {
   611  		t.Fatalf(Format, "Error after update 1 - Not updated properly", "UPDATE 1", p.Title)
   612  	}
   613  
   614  }
   615  
   616  // Some more damaging operations we execute at the end,
   617  // to avoid having to reload the db for each test
   618  
   619  func TestMysqlUpdateAll(t *testing.T) {
   620  
   621  	err := PagesQuery().UpdateAll(map[string]string{"title": "test me"})
   622  	if err != nil {
   623  		t.Fatalf(Format, "UPDATE ALL err", "udpate all records", err)
   624  	}
   625  
   626  	// Check we have all pages with same title
   627  	count, err := PagesQuery().Where("title=?", "test me").Count()
   628  
   629  	if err != nil || count != 3 {
   630  		t.Fatalf(Format, "Count after update all", "3", fmt.Sprintf("%d", count))
   631  	}
   632  
   633  }
   634  
   635  func TestMysqlCreate(t *testing.T) {
   636  
   637  	params := map[string]string{
   638  		"title":      "Test 98",
   639  		"text":       "My text",
   640  		"created_at": "REPLACE ME",
   641  		"summary":    "me",
   642  	}
   643  
   644  	// if your model is in a package, it could be pages.Create()
   645  	// For now to mock we just use an empty page
   646  	id, err := (&Page{}).Create(params)
   647  	if err != nil {
   648  		t.Fatalf(Format, "Err on create", err)
   649  	}
   650  
   651  	// Now find the page and test it
   652  	p, err := PagesFind(id)
   653  	if err != nil {
   654  		t.Fatalf(Format, "Err on create find", err)
   655  	}
   656  
   657  	if p.Text != "My text" {
   658  		t.Fatalf(Format, "Create page params mismatch", "Creation", p.ID)
   659  	}
   660  
   661  	// Check we have one left
   662  	count, err := PagesQuery().Count()
   663  
   664  	if err != nil || count != 4 {
   665  		t.Fatalf(Format, "Count after create", "4", fmt.Sprintf("%d", count))
   666  	}
   667  
   668  }
   669  
   670  func TestMysqlDelete(t *testing.T) {
   671  
   672  	p, err := PagesFind(3)
   673  	if err != nil {
   674  		t.Fatalf(Format, "Could not find model err", "id-3", err)
   675  	}
   676  	err = p.Delete()
   677  	if err != nil {
   678  		t.Fatalf(Format, "Error after delete", "deleted", err)
   679  	}
   680  
   681  	// Check it is gone and we get an error on next find
   682  	p, err = PagesFind(3)
   683  	if !strings.Contains(fmt.Sprintf("%s", err), "No results found") {
   684  		t.Fatalf(Format, "Error after delete 1", "1", err)
   685  	}
   686  
   687  }
   688  
   689  func TestMysqlDeleteAll(t *testing.T) {
   690  
   691  	err := PagesQuery().Where("id > 1").DeleteAll()
   692  	if err != nil {
   693  		t.Fatalf(Format, "DELETE ALL err", "delete 2 records", err)
   694  	}
   695  
   696  	// Check we have one left
   697  	count, err := PagesQuery().Where("id > 0").Count()
   698  
   699  	if err != nil || count != 1 {
   700  		t.Fatalf(Format, "Count after delete all", "1", fmt.Sprintf("%d", count))
   701  	}
   702  
   703  }
   704  
   705  func TestMysqlTeardown(t *testing.T) {
   706  
   707  	err := CloseDatabase()
   708  	if err != nil {
   709  		fmt.Println("Close DB ERROR ", err)
   710  	}
   711  }
   712  
   713  /*
   714  // See note in adapters/database_sqlite.go for reasons this is disabled
   715  // ----------------------------------
   716  // SQLITE TESTS
   717  // ----------------------------------
   718  
   719  func TestSQSetup(t *testing.T) {
   720  
   721  	fmt.Println("\n---\nTESTING SQLITE\n---")
   722  
   723  	// NB we use binary named sqlite3 - this is the default on OS X
   724  	// NB this requires sqlite3 version > 3.7.15 for init alternative would be to echo sql file at end
   725  	cmd := exec.Command("sqlite3", "--init", "tests/query_test_sqlite.sql", "tests/query_test.sqlite")
   726  	stdout, _ := cmd.StdoutPipe()
   727  	stderr, _ := cmd.StderrPipe()
   728  	err = cmd.Start()
   729  	if err != nil {
   730  		fmt.Println("Could not set up sqlite db - ERROR ", err)
   731  		os.Exit(1)
   732  	}
   733  	go io.Copy(os.Stdout, stdout)
   734  	go io.Copy(os.Stderr, stderr)
   735  	cmd.Wait()
   736  
   737  	if err == nil {
   738  		_ = strings.Replace("", "", "", -1)
   739  
   740  		// Open the database
   741  		options := map[string]string{
   742  			"adapter": "sqlite3",
   743  			"db":      "tests/query_test.sqlite",
   744  			"debug":   "true", // for more detail on failure, enable debug mode on db
   745  		}
   746  
   747  		err = OpenDatabase(options)
   748  		if err != nil {
   749  			fmt.Println("Open database ERROR ", err)
   750  			os.Exit(1)
   751  		}
   752  
   753  		fmt.Println("---\nQuery Testing Sqlite3 - DB setup complete\n---")
   754  	}
   755  
   756  }
   757  
   758  func TestSQFind(t *testing.T) {
   759  
   760  	// This should work - NB in normal usage this would be query.New
   761  	p, err := PagesFind(1)
   762  	if err != nil {
   763  		t.Fatalf(Format, "Find(1)", "Model object", err)
   764  	}
   765  	// Check we got the page we expect
   766  	if p.ID != 1 {
   767  		t.Fatalf(Format, "Find(1) p", "Model object", p)
   768  	}
   769  
   770  	// This should fail, so we check that
   771  	p, err = PagesFind(11)
   772  	if err == nil || p != nil {
   773  		t.Fatalf(Format, "Find(11)", "Model object", err)
   774  	}
   775  
   776  }
   777  
   778  func TestSQCount(t *testing.T) {
   779  
   780  	// This should return 3
   781  	count, err := PagesQuery().Count()
   782  	if err != nil || count != 3 {
   783  		t.Fatalf(Format, "Count failed", "3", fmt.Sprintf("%d", count))
   784  	}
   785  
   786  	// This should return 2 - test limit ignored
   787  	count, err = PagesQuery().Where("id in (?,?)", 1, 2).Order("id desc").Limit(100).Count()
   788  	if err != nil || count != 2 {
   789  		t.Fatalf(Format, "Count id < 3 failed", "2", fmt.Sprintf("%d", count))
   790  	}
   791  
   792  	// This should return 0
   793  	count, err = PagesQuery().Where("id > 3").Count()
   794  	if err != nil || count != 0 {
   795  		t.Fatalf(Format, "Count id > 3 failed", "0", fmt.Sprintf("%d", count))
   796  	}
   797  
   798  	// Test retrieving an array, then counting, then where
   799  	// This should work
   800  	q := PagesQuery().Where("id > ?", 1).Order("id desc")
   801  
   802  	count, err = q.Count()
   803  	if err != nil || count != 2 {
   804  		t.Fatalf(Format, "Count id > 1 failed", "2", fmt.Sprintf("%d", count), err)
   805  	}
   806  
   807  	// Reuse same query to get array after count
   808  	results, err := q.Results()
   809  	if err != nil || len(results) != 2 {
   810  		t.Fatalf(Format, "Where Array after count", "len 2", err)
   811  	}
   812  
   813  }
   814  
   815  func TestSQWhere(t *testing.T) {
   816  
   817  	q := PagesQuery().Where("id > ?", 1)
   818  	pages, err := PagesFindAll(q)
   819  
   820  	if err != nil || len(pages) != 2 {
   821  		t.Fatalf(Format, "Where Array", "len 2", fmt.Sprintf("%d", len(pages)))
   822  	}
   823  
   824  }
   825  
   826  func TestSQOrder(t *testing.T) {
   827  
   828  	// Look for pages in reverse order
   829  	var models []*Page
   830  	q := PagesQuery().Where("id > 0").Order("id desc")
   831  	models, err := PagesFindAll(q)
   832  
   833  	if err != nil || len(models) == 0 {
   834  		t.Fatalf(Format, "Order count test id desc", "3", fmt.Sprintf("%d", len(models)))
   835  		return
   836  	}
   837  
   838  	p := models[0]
   839  	if p.ID != 3 {
   840  		t.Fatalf(Format, "Order test id desc 1", "3", fmt.Sprintf("%d", p.ID))
   841  		return
   842  	}
   843  
   844  	// Look for pages in right order - reset models
   845  	q = PagesQuery().Where("id < ?", 10).Where("id < ?", 100).Order("id asc")
   846  	models, err = PagesFindAll(q)
   847  	//   fmt.Println("TESTING MODELS %v",models)
   848  
   849  	if err != nil || models == nil {
   850  		t.Fatalf(Format, "Order test id asc count", "1", err)
   851  	}
   852  
   853  	p = models[0]
   854  	if p.ID != 1 {
   855  		t.Fatalf(Format, "Order test id asc 1", "1", fmt.Sprintf("%d", p.ID))
   856  		return
   857  	}
   858  
   859  }
   860  
   861  func TestSQSelect(t *testing.T) {
   862  
   863  	var models []*Page
   864  	q := PagesQuery().Select("SELECT id,title from pages").Order("id asc")
   865  	models, err := PagesFindAll(q)
   866  	if err != nil || len(models) == 0 {
   867  		t.Fatalf(Format, "Select error on id,title", "id,title", err)
   868  	}
   869  	p := models[0]
   870  	if p.ID != 1 || p.Title != "Title 1." || len(p.Text) > 0 {
   871  		t.Fatalf(Format, "Select id,title", "id,title only", p)
   872  	}
   873  
   874  }
   875  
   876  func TestSQUpdate(t *testing.T) {
   877  
   878  	p, err := PagesFind(3)
   879  	if err != nil {
   880  		t.Fatalf(Format, "Update could not find model err", "id-3", err)
   881  	}
   882  
   883  	// Should really test updates with several strings here
   884  	err = p.Update(map[string]string{"title": "UPDATE 1", "summary": "Test summary"})
   885  
   886  	// Check it is modified
   887  	p, err = PagesFind(3)
   888  
   889  	if err != nil {
   890  		t.Fatalf(Format, "Error after update 1", "updated", err)
   891  	}
   892  
   893  	if p.Title != "UPDATE 1" {
   894  		t.Fatalf(Format, "Error after update 1 - Not updated properly", "UPDATE 1", p.Title)
   895  	}
   896  
   897  }
   898  
   899  // Some more damaging operations we execute at the end,
   900  // to avoid having to reload the db for each test
   901  
   902  func TestSQUpdateAll(t *testing.T) {
   903  
   904  	err := PagesQuery().UpdateAll(map[string]string{"title": "test me"})
   905  	if err != nil {
   906  		t.Fatalf(Format, "UPDATE ALL err", "udpate all records", err)
   907  	}
   908  
   909  	// Check we have all pages with same title
   910  	count, err := PagesQuery().Where("title=?", "test me").Count()
   911  
   912  	if err != nil || count != 3 {
   913  		t.Fatalf(Format, "Count after update all", "3", fmt.Sprintf("%d", count))
   914  	}
   915  
   916  }
   917  
   918  func TestSQCreate(t *testing.T) {
   919  
   920  	params := map[string]string{
   921  		"title":      "Test 98",
   922  		"text":       "My text",
   923  		"created_at": "REPLACE ME",
   924  		"summary":    "me",
   925  	}
   926  
   927  	// if your model is in a package, it could be pages.Create()
   928  	// For now to mock we just use an empty page
   929  	id, err := (&Page{}).Create(params)
   930  	if err != nil {
   931  		t.Fatalf(Format, "Err on create", err)
   932  	}
   933  
   934  	// Now find the page and test it
   935  	p, err := PagesFind(id)
   936  	if err != nil {
   937  		t.Fatalf(Format, "Err on create find", err)
   938  	}
   939  
   940  	if p.Title != "Test 98" {
   941  		t.Fatalf(Format, "Create page params mismatch", "Creation", p.ID)
   942  	}
   943  
   944  	// Check we have one left
   945  	count, err := PagesQuery().Count()
   946  
   947  	if err != nil || count != 4 {
   948  		t.Fatalf(Format, "Count after create", "4", fmt.Sprintf("%d", count))
   949  	}
   950  
   951  }
   952  
   953  func TestSQDelete(t *testing.T) {
   954  
   955  	p, err := PagesFind(3)
   956  	if err != nil {
   957  		t.Fatalf(Format, "Could not find model err", "id-3", err)
   958  	}
   959  
   960  	err = p.Delete()
   961  
   962  	// Check it is gone and we get an error on next find
   963  	p, err = PagesFind(3)
   964  
   965  	if !strings.Contains(fmt.Sprintf("%s", err), "No results found") {
   966  		t.Fatalf(Format, "Error after delete 1", "1", err)
   967  	}
   968  
   969  }
   970  
   971  func TestSQDeleteAll(t *testing.T) {
   972  
   973  	err := PagesQuery().Where("id > 1").DeleteAll()
   974  	if err != nil {
   975  		t.Fatalf(Format, "DELETE ALL err", "delete 2 records", err)
   976  	}
   977  
   978  	// Check we have one left
   979  	count, err := PagesQuery().Where("id > 0").Count()
   980  
   981  	if err != nil || count != 1 {
   982  		t.Fatalf(Format, "Count after delete all", "1", fmt.Sprintf("%d", count))
   983  	}
   984  
   985  }
   986  
   987  func TestSQTeardown(t *testing.T) {
   988  
   989  	err := CloseDatabase()
   990  	if err != nil {
   991  		fmt.Println("Close DB ERROR ", err)
   992  	}
   993  }
   994  */