d3d9: Fix the type of three loop variables.
[wine] / dlls / msi / database.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38
39 #include "initguid.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(msi);
42
43 DEFINE_GUID( CLSID_MsiDatabase, 0x000c1084, 0x0000, 0x0000,
44              0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
45 DEFINE_GUID( CLSID_MsiPatch, 0x000c1086, 0x0000, 0x0000,
46              0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
47
48 /*
49  *  .MSI  file format
50  *
51  *  An .msi file is a structured storage file.
52  *  It contains a number of streams.
53  *  A stream for each table in the database.
54  *  Two streams for the string table in the database.
55  *  Any binary data in a table is a reference to a stream.
56  */
57
58 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
59 {
60     MSIDATABASE *db = (MSIDATABASE *) arg;
61
62     msi_free(db->path);
63     free_cached_tables( db );
64     msi_free_transforms( db );
65     msi_destroy_stringtable( db->strings );
66     IStorage_Release( db->storage );
67     if (db->deletefile)
68     {
69         DeleteFileW( db->deletefile );
70         msi_free( db->deletefile );
71     }
72 }
73
74 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
75 {
76     IStorage *stg = NULL;
77     HRESULT r;
78     MSIDATABASE *db = NULL;
79     UINT ret = ERROR_FUNCTION_FAILED;
80     LPCWSTR szMode, save_path;
81     STATSTG stat;
82     BOOL created = FALSE;
83     WCHAR path[MAX_PATH];
84
85     static const WCHAR backslash[] = {'\\',0};
86     static WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
87
88     TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
89
90     if( !pdb )
91         return ERROR_INVALID_PARAMETER;
92
93     save_path = szDBPath;
94     szMode = szPersist;
95     if( HIWORD( szPersist ) )
96     {
97         if (!CopyFileW( szDBPath, szPersist, FALSE ))
98             return ERROR_OPEN_FAILED;
99
100         szDBPath = szPersist;
101         szPersist = MSIDBOPEN_TRANSACT;
102         created = TRUE;
103     }
104
105     if( szPersist == MSIDBOPEN_READONLY )
106     {
107         r = StgOpenStorage( szDBPath, NULL,
108               STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
109     }
110     else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
111     {
112         /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
113          * used here: */
114         r = StgCreateDocfile( szDBPath,
115               STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
116         if( r == ERROR_SUCCESS )
117         {
118             IStorage_SetClass( stg, &CLSID_MsiDatabase );
119             /* create the _Tables stream */
120             r = write_stream_data(stg, szTables, NULL, 0, TRUE);
121             if (!FAILED(r))
122                 r = msi_init_string_table( stg );
123         }
124         created = TRUE;
125     }
126     else if( szPersist == MSIDBOPEN_TRANSACT )
127     {
128         /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
129          * used here: */
130         r = StgOpenStorage( szDBPath, NULL,
131               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
132     }
133     else if( szPersist == MSIDBOPEN_DIRECT )
134     {
135         r = StgOpenStorage( szDBPath, NULL,
136               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
137     }
138     else
139     {
140         ERR("unknown flag %p\n",szPersist);
141         return ERROR_INVALID_PARAMETER;
142     }
143
144     if( FAILED( r ) || !stg )
145     {
146         FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
147         return ERROR_FUNCTION_FAILED;
148     }
149
150     r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
151     if( FAILED( r ) )
152     {
153         FIXME("Failed to stat storage\n");
154         goto end;
155     }
156
157     if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
158          !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) ) 
159     {
160         ERR("storage GUID is not a MSI database GUID %s\n",
161              debugstr_guid(&stat.clsid) );
162         goto end;
163     }
164
165     db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
166                               MSI_CloseDatabase );
167     if( !db )
168     {
169         FIXME("Failed to allocate a handle\n");
170         goto end;
171     }
172
173     if (!strchrW( save_path, '\\' ))
174     {
175         GetCurrentDirectoryW( MAX_PATH, path );
176         lstrcatW( path, backslash );
177         lstrcatW( path, save_path );
178     }
179     else
180         lstrcpyW( path, save_path );
181
182     db->path = strdupW( path );
183
184     if( TRACE_ON( msi ) )
185         enum_stream_names( stg );
186
187     db->storage = stg;
188     db->mode = szMode;
189     if (created)
190         db->deletefile = strdupW( szDBPath );
191     else
192         db->deletefile = NULL;
193     list_init( &db->tables );
194     list_init( &db->transforms );
195
196     db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
197     if( !db->strings )
198         goto end;
199
200     msi_table_set_strref( db->bytes_per_strref );
201     ret = ERROR_SUCCESS;
202
203     msiobj_addref( &db->hdr );
204     IStorage_AddRef( stg );
205     *pdb = db;
206
207 end:
208     if( db )
209         msiobj_release( &db->hdr );
210     if( stg )
211         IStorage_Release( stg );
212
213     return ret;
214 }
215
216 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
217 {
218     MSIDATABASE *db;
219     UINT ret;
220
221     TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
222
223     ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
224     if( ret == ERROR_SUCCESS )
225     {
226         *phDB = alloc_msihandle( &db->hdr );
227         if (! *phDB)
228             ret = ERROR_NOT_ENOUGH_MEMORY;
229         msiobj_release( &db->hdr );
230     }
231
232     return ret;
233 }
234
235 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
236 {
237     HRESULT r = ERROR_FUNCTION_FAILED;
238     LPWSTR szwDBPath = NULL, szwPersist = NULL;
239
240     TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
241
242     if( szDBPath )
243     {
244         szwDBPath = strdupAtoW( szDBPath );
245         if( !szwDBPath )
246             goto end;
247     }
248
249     if( HIWORD(szPersist) )
250     {
251         szwPersist = strdupAtoW( szPersist );
252         if( !szwPersist )
253             goto end;
254     }
255     else
256         szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
257
258     r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
259
260 end:
261     if( HIWORD(szPersist) )
262         msi_free( szwPersist );
263     msi_free( szwDBPath );
264
265     return r;
266 }
267
268 static LPWSTR msi_read_text_archive(LPCWSTR path)
269 {
270     HANDLE file;
271     LPSTR data = NULL;
272     LPWSTR wdata = NULL;
273     DWORD read, size = 0;
274
275     file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
276     if (file == INVALID_HANDLE_VALUE)
277         return NULL;
278
279     size = GetFileSize( file, NULL );
280     data = msi_alloc( size + 1 );
281     if (!data)
282         goto done;
283
284     if (!ReadFile( file, data, size, &read, NULL ))
285         goto done;
286
287     data[size] = '\0';
288     wdata = strdupAtoW( data );
289
290 done:
291     CloseHandle( file );
292     msi_free( data );
293     return wdata;
294 }
295
296 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
297 {
298     LPWSTR ptr = *line, save;
299     DWORD i, count = 1;
300
301     *entries = NULL;
302
303     /* stay on this line */
304     while (*ptr && *ptr != '\n')
305     {
306         /* entries are separated by tabs */
307         if (*ptr == '\t')
308             count++;
309
310         ptr++;
311     }
312
313     *entries = msi_alloc(count * sizeof(LPWSTR));
314     if (!*entries)
315         return;
316
317     /* store pointers into the data */
318     for (i = 0, ptr = *line; i < count; i++)
319     {
320         save = ptr;
321
322         while (*ptr && *ptr != '\t' && *ptr != '\n') ptr++;
323
324         /* NULL-separate the data */
325         if (*ptr)
326             *ptr++ = '\0';
327
328         (*entries)[i] = save;
329     }
330
331     /* move to the next line if there's more, else EOF */
332     *line = ptr;
333
334     if (num_entries)
335         *num_entries = count;
336 }
337
338 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
339 {
340     LPWSTR prelude;
341     DWORD size;
342
343     static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
344
345     size = sizeof(create_fmt) + lstrlenW(table) - 2;
346     prelude = msi_alloc(size * sizeof(WCHAR));
347     if (!prelude)
348         return NULL;
349
350     sprintfW(prelude, create_fmt, table);
351     return prelude;
352 }
353
354 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
355 {
356     LPWSTR columns, p;
357     LPCWSTR type;
358     DWORD sql_size = 1, i, len;
359     WCHAR expanded[128], *ptr;
360     WCHAR size[10], comma[2], extra[30];
361
362     static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
363     static const WCHAR size_fmt[] = {'(','%','s',')',0};
364     static const WCHAR type_char[] = {'C','H','A','R',0};
365     static const WCHAR type_int[] = {'I','N','T',0};
366     static const WCHAR type_long[] = {'L','O','N','G',0};
367     static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
368     static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
369
370     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
371     if (!columns)
372         return NULL;
373
374     for (i = 0; i < num_columns; i++)
375     {
376         type = NULL;
377         comma[1] = size[0] = extra[0] = '\0';
378
379         if (i == num_columns - 1)
380             comma[0] = '\0';
381         else
382             comma[0] = ',';
383
384         ptr = &types[i][1];
385         len = atolW(ptr);
386         extra[0] = '\0';
387
388         switch (types[i][0])
389         {
390             case 'l':
391                 lstrcpyW(extra, type_notnull);
392             case 'L':
393                 lstrcatW(extra, localizable);
394                 type = type_char;
395                 sprintfW(size, size_fmt, ptr);
396                 break;
397             case 's':
398                 lstrcpyW(extra, type_notnull);
399             case 'S':
400                 type = type_char;
401                 sprintfW(size, size_fmt, ptr);
402                 break;
403             case 'i':
404                 lstrcpyW(extra, type_notnull);
405             case 'I':
406                 if (len == 2)
407                     type = type_int;
408                 else
409                     type = type_long;
410                 break;
411         }
412
413         sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
414         sql_size += lstrlenW(expanded);
415
416         p = msi_realloc(columns, sql_size * sizeof(WCHAR));
417         if (!p)
418         {
419             msi_free(columns);
420             return NULL;
421         }
422         columns = p;
423
424         lstrcatW(columns, expanded);
425     }
426
427     return columns;
428 }
429
430 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
431 {
432     LPWSTR postlude, keys, ptr;
433     DWORD size, key_size, i;
434
435     static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
436     static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
437
438     for (i = 0, size = 1; i < num_keys; i++)
439         size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
440
441     keys = msi_alloc(size * sizeof(WCHAR));
442     if (!keys)
443         return NULL;
444
445     for (i = 0, ptr = keys; i < num_keys; i++)
446     {
447         key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
448         sprintfW(ptr, key_fmt, primary_keys[i]);
449         ptr += key_size;
450     }
451
452     /* remove final ', ' */
453     *(ptr - 2) = '\0';
454
455     size = lstrlenW(postlude_fmt) + size - 1;
456     postlude = msi_alloc(size * sizeof(WCHAR));
457     if (!postlude)
458         goto done;
459
460     sprintfW(postlude, postlude_fmt, keys);
461
462 done:
463     msi_free(keys);
464     return postlude;
465 }
466
467 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
468 {
469     UINT r;
470     DWORD size;
471     MSIQUERY *view;
472     LPWSTR create_sql;
473     LPWSTR prelude, columns_sql, postlude;
474
475     prelude = msi_build_createsql_prelude(labels[0]);
476     columns_sql = msi_build_createsql_columns(columns, types, num_columns);
477     postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
478
479     if (!prelude || !columns_sql || !postlude)
480         return ERROR_OUTOFMEMORY;
481
482     size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
483     create_sql = msi_alloc(size * sizeof(WCHAR));
484     if (!create_sql)
485         return ERROR_OUTOFMEMORY;
486
487     lstrcpyW(create_sql, prelude);
488     lstrcatW(create_sql, columns_sql);
489     lstrcatW(create_sql, postlude);
490
491     msi_free(prelude);
492     msi_free(columns_sql);
493     msi_free(postlude);
494
495     r = MSI_DatabaseOpenViewW( db, create_sql, &view );
496     msi_free(create_sql);
497
498     if (r != ERROR_SUCCESS)
499         return r;
500
501     r = MSI_ViewExecute(view, NULL);
502     MSI_ViewClose(view);
503     msiobj_release(&view->hdr);
504
505     return r;
506 }
507
508 static LPWSTR msi_build_insertsql_prelude(LPWSTR table)
509 {
510     LPWSTR prelude;
511     DWORD size;
512
513     static const WCHAR insert_fmt[] = {'I','N','S','E','R','T',' ','I','N','T','O',' ','`','%','s','`',' ','(',' ',0};
514
515     size = sizeof(insert_fmt) + lstrlenW(table) - 2;
516     prelude = msi_alloc(size * sizeof(WCHAR));
517     if (!prelude)
518         return NULL;
519
520     sprintfW(prelude, insert_fmt, table);
521     return prelude;
522 }
523
524 static LPWSTR msi_build_insertsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
525 {
526     LPWSTR columns, p;
527     DWORD sql_size = 1, i;
528     WCHAR expanded[128];
529
530     static const WCHAR column_fmt[] =  {'`','%','s','`',',',' ',0};
531
532     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
533     if (!columns)
534         return NULL;
535
536     for (i = 0; i < num_columns; i++)
537     {
538         sprintfW(expanded, column_fmt, columns_data[i]);
539         sql_size += lstrlenW(expanded);
540
541         if (i == num_columns - 1)
542         {
543             sql_size -= 2;
544             expanded[lstrlenW(expanded) - 2] = '\0';
545         }
546
547         p = msi_realloc(columns, sql_size * sizeof(WCHAR));
548         if (!p)
549         {
550             msi_free(columns);
551             return NULL;
552         }
553         columns = p;
554
555         lstrcatW(columns, expanded);
556     }
557
558     return columns;
559 }
560
561 static LPWSTR msi_build_insertsql_data(LPWSTR **records, LPWSTR *types, DWORD num_columns, DWORD irec)
562 {
563     LPWSTR columns, temp_columns;
564     DWORD sql_size = 1, i;
565     WCHAR expanded[128];
566
567     static const WCHAR str_fmt[] = {'\'','%','s','\'',',',' ',0};
568     static const WCHAR int_fmt[] = {'%','s',',',' ',0};
569     static const WCHAR empty[] = {'\'','\'',',',' ',0};
570
571     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
572     if (!columns)
573         return NULL;
574
575     for (i = 0; i < num_columns; i++)
576     {
577         switch (types[i][0])
578         {
579             case 'L': case 'l': case 'S': case 's':
580                 sprintfW(expanded, str_fmt, records[irec][i]);
581                 break;
582             case 'I': case 'i':
583                 if (*records[0][i])
584                     sprintfW(expanded, int_fmt, records[irec][i]);
585                 else
586                     lstrcpyW(expanded, empty);
587                 break;
588             default:
589                 HeapFree( GetProcessHeap(), 0, columns );
590                 return NULL;
591         }
592
593         if (i == num_columns - 1)
594             expanded[lstrlenW(expanded) - 2] = '\0';
595
596         sql_size += lstrlenW(expanded);
597         temp_columns = msi_realloc(columns, sql_size * sizeof(WCHAR));
598         if (!temp_columns)
599         {
600             HeapFree( GetProcessHeap(), 0, columns);
601             return NULL;
602         }
603         columns = temp_columns;
604
605         lstrcatW(columns, expanded);
606     }
607
608     return columns;
609 }
610
611 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
612                                      LPWSTR *labels, LPWSTR **records,
613                                      int num_columns, int num_records)
614 {
615     MSIQUERY *view;
616     LPWSTR insert_sql;
617     DWORD size, i;
618     UINT r = ERROR_SUCCESS;
619
620     static const WCHAR mid[] = {' ',')',' ','V','A','L','U','E','S',' ','(',' ',0};
621     static const WCHAR end[] = {' ',')',0};
622
623     LPWSTR prelude = msi_build_insertsql_prelude(labels[0]);
624     LPWSTR columns_sql = msi_build_insertsql_columns(columns, types, num_columns);
625     
626     for (i = 0; i < num_records; i++)
627     {
628         LPWSTR data = msi_build_insertsql_data(records, types, num_columns, i);
629
630         size = lstrlenW(prelude) + lstrlenW(columns_sql) + sizeof(mid) + lstrlenW(data) + sizeof(end) - 1; 
631         insert_sql = msi_alloc(size * sizeof(WCHAR));
632         if (!insert_sql)
633             return ERROR_OUTOFMEMORY;
634     
635         lstrcpyW(insert_sql, prelude);
636         lstrcatW(insert_sql, columns_sql);
637         lstrcatW(insert_sql, mid);
638         lstrcatW(insert_sql, data);
639         lstrcatW(insert_sql, end);
640
641         msi_free(data);
642
643         r = MSI_DatabaseOpenViewW( db, insert_sql, &view );
644         msi_free(insert_sql);
645
646         if (r != ERROR_SUCCESS)
647             goto done;
648
649         r = MSI_ViewExecute(view, NULL);
650         MSI_ViewClose(view);
651         msiobj_release(&view->hdr);
652     }
653
654 done:
655     msi_free(prelude);
656     msi_free(columns_sql);
657
658     return r;
659 }
660
661 UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
662 {
663     UINT r;
664     DWORD len, i;
665     DWORD num_labels;
666     DWORD num_columns, num_records = 0;
667     LPWSTR *columns, *types, *labels;
668     LPWSTR path, ptr, data;
669     LPWSTR **records;
670     LPWSTR **temp_records;
671
672     static const WCHAR backslash[] = {'\\',0};
673
674     TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
675
676     if( folder == NULL || file == NULL )
677         return ERROR_INVALID_PARAMETER;
678
679     len = lstrlenW(folder) + lstrlenW(backslash) + lstrlenW(file) + 1;
680     path = msi_alloc( len * sizeof(WCHAR) );
681     if (!path)
682         return ERROR_OUTOFMEMORY;
683
684     lstrcpyW( path, folder );
685     lstrcatW( path, backslash );
686     lstrcatW( path, file );
687
688     data = msi_read_text_archive( path );
689
690     ptr = data;
691     msi_parse_line( &ptr, &columns, &num_columns );
692     msi_parse_line( &ptr, &types, NULL );
693     msi_parse_line( &ptr, &labels, &num_labels );
694
695     records = msi_alloc(sizeof(LPWSTR *));
696     if (!records)
697     {
698         r = ERROR_OUTOFMEMORY;
699         goto done;
700     }
701
702     /* read in the table records */
703     while (*ptr)
704     {
705         msi_parse_line( &ptr, &records[num_records], NULL );
706
707         num_records++;
708         temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
709         if (!temp_records)
710         {
711             r = ERROR_OUTOFMEMORY;
712             goto done;
713         }
714         records = temp_records;
715     }
716
717     r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
718     if (r != ERROR_SUCCESS)
719         goto done;
720
721     r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records );
722
723 done:
724     msi_free(path);
725     msi_free(data);
726     msi_free(columns);
727     msi_free(types);
728     msi_free(labels);
729
730     for (i = 0; i < num_records; i++)
731         msi_free(records[i]);
732
733     msi_free(records);
734
735     return r;
736 }
737
738 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
739 {
740     MSIDATABASE *db;
741     UINT r;
742
743     TRACE("%lx %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
744
745     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
746     if( !db )
747     {
748         IWineMsiRemoteDatabase *remote_database;
749
750         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
751         if ( !remote_database )
752             return ERROR_INVALID_HANDLE;
753
754         IWineMsiRemoteDatabase_Release( remote_database );
755         WARN("MsiDatabaseImport not allowed during a custom action!\n");
756
757         return ERROR_SUCCESS;
758     }
759
760     r = MSI_DatabaseImport( db, szFolder, szFilename );
761     msiobj_release( &db->hdr );
762     return r;
763 }
764
765 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
766                LPCSTR szFolder, LPCSTR szFilename )
767 {
768     LPWSTR path = NULL, file = NULL;
769     UINT r = ERROR_OUTOFMEMORY;
770
771     TRACE("%lx %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
772
773     if( szFolder )
774     {
775         path = strdupAtoW( szFolder );
776         if( !path )
777             goto end;
778     }
779
780     if( szFilename )
781     {
782         file = strdupAtoW( szFilename );
783         if( !file )
784             goto end;
785     }
786
787     r = MsiDatabaseImportW( handle, path, file );
788
789 end:
790     msi_free( path );
791     msi_free( file );
792
793     return r;
794 }
795
796 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
797 {
798     UINT i, count, len, r = ERROR_SUCCESS;
799     const char *sep;
800     char *buffer;
801     DWORD sz;
802
803     len = 0x100;
804     buffer = msi_alloc( len );
805     if ( !buffer )
806         return ERROR_OUTOFMEMORY;
807
808     count = MSI_RecordGetFieldCount( row );
809     for ( i=start; i<=count; i++ )
810     {
811         sz = len;
812         r = MSI_RecordGetStringA( row, i, buffer, &sz );
813         if (r == ERROR_MORE_DATA)
814         {
815             char *p = msi_realloc( buffer, sz + 1 );
816             if (!p)
817                 break;
818             len = sz + 1;
819             buffer = p;
820         }
821         sz = len;
822         r = MSI_RecordGetStringA( row, i, buffer, &sz );
823         if (r != ERROR_SUCCESS)
824             break;
825
826         if (!WriteFile( handle, buffer, sz, &sz, NULL ))
827         {
828             r = ERROR_FUNCTION_FAILED;
829             break;
830         }
831
832         sep = (i < count) ? "\t" : "\r\n";
833         if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
834         {
835             r = ERROR_FUNCTION_FAILED;
836             break;
837         }
838     }
839     msi_free( buffer );
840     return r;
841 }
842
843 static UINT msi_export_row( MSIRECORD *row, void *arg )
844 {
845     return msi_export_record( arg, row, 1 );
846 }
847
848 UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
849                LPCWSTR folder, LPCWSTR file )
850 {
851     static const WCHAR query[] = {
852         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
853     static const WCHAR szbs[] = { '\\', 0 };
854     MSIRECORD *rec = NULL;
855     MSIQUERY *view = NULL;
856     LPWSTR filename;
857     HANDLE handle;
858     UINT len, r;
859
860     TRACE("%p %s %s %s\n", db, debugstr_w(table),
861           debugstr_w(folder), debugstr_w(file) );
862
863     if( folder == NULL || file == NULL )
864         return ERROR_INVALID_PARAMETER;
865
866     len = lstrlenW(folder) + lstrlenW(file) + 2;
867     filename = msi_alloc(len * sizeof (WCHAR));
868     if (!filename)
869         return ERROR_OUTOFMEMORY;
870
871     lstrcpyW( filename, folder );
872     lstrcatW( filename, szbs );
873     lstrcatW( filename, file );
874
875     handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
876                           NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
877     msi_free( filename );
878     if (handle == INVALID_HANDLE_VALUE)
879         return ERROR_FUNCTION_FAILED;
880
881     r = MSI_OpenQuery( db, &view, query, table );
882     if (r == ERROR_SUCCESS)
883     {
884         /* write out row 1, the column names */
885         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
886         if (r == ERROR_SUCCESS)
887         {
888             msi_export_record( handle, rec, 1 );
889             msiobj_release( &rec->hdr );
890         }
891
892         /* write out row 2, the column types */
893         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
894         if (r == ERROR_SUCCESS)
895         {
896             msi_export_record( handle, rec, 1 );
897             msiobj_release( &rec->hdr );
898         }
899
900         /* write out row 3, the table name + keys */
901         r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
902         if (r == ERROR_SUCCESS)
903         {
904             MSI_RecordSetStringW( rec, 0, table );
905             msi_export_record( handle, rec, 0 );
906             msiobj_release( &rec->hdr );
907         }
908
909         /* write out row 4 onwards, the data */
910         r = MSI_IterateRecords( view, 0, msi_export_row, handle );
911         msiobj_release( &view->hdr );
912     }
913
914     CloseHandle( handle );
915
916     return r;
917 }
918
919 /***********************************************************************
920  * MsiExportDatabaseW        [MSI.@]
921  *
922  * Writes a file containing the table data as tab separated ASCII.
923  *
924  * The format is as follows:
925  *
926  * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
927  * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
928  * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
929  *
930  * Followed by the data, starting at row 1 with one row per line
931  *
932  * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
933  */
934 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
935                LPCWSTR szFolder, LPCWSTR szFilename )
936 {
937     MSIDATABASE *db;
938     UINT r;
939
940     TRACE("%lx %s %s %s\n", handle, debugstr_w(szTable),
941           debugstr_w(szFolder), debugstr_w(szFilename));
942
943     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
944     if( !db )
945     {
946         IWineMsiRemoteDatabase *remote_database;
947
948         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
949         if ( !remote_database )
950             return ERROR_INVALID_HANDLE;
951
952         IWineMsiRemoteDatabase_Release( remote_database );
953         WARN("MsiDatabaseExport not allowed during a custom action!\n");
954
955         return ERROR_SUCCESS;
956     }
957
958     r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
959     msiobj_release( &db->hdr );
960     return r;
961 }
962
963 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
964                LPCSTR szFolder, LPCSTR szFilename )
965 {
966     LPWSTR path = NULL, file = NULL, table = NULL;
967     UINT r = ERROR_OUTOFMEMORY;
968
969     TRACE("%lx %s %s %s\n", handle, debugstr_a(szTable),
970           debugstr_a(szFolder), debugstr_a(szFilename));
971
972     if( szTable )
973     {
974         table = strdupAtoW( szTable );
975         if( !table )
976             goto end;
977     }
978
979     if( szFolder )
980     {
981         path = strdupAtoW( szFolder );
982         if( !path )
983             goto end;
984     }
985
986     if( szFilename )
987     {
988         file = strdupAtoW( szFilename );
989         if( !file )
990             goto end;
991     }
992
993     r = MsiDatabaseExportW( handle, table, path, file );
994
995 end:
996     msi_free( table );
997     msi_free( path );
998     msi_free( file );
999
1000     return r;
1001 }
1002
1003 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1004 {
1005     MSIDBSTATE ret = MSIDBSTATE_READ;
1006     MSIDATABASE *db;
1007
1008     TRACE("%ld\n", handle);
1009
1010     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1011     if( !db )
1012     {
1013         IWineMsiRemoteDatabase *remote_database;
1014
1015         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1016         if ( !remote_database )
1017             return MSIDBSTATE_ERROR;
1018
1019         IWineMsiRemoteDatabase_Release( remote_database );
1020         WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1021
1022         return MSIDBSTATE_READ;
1023     }
1024
1025     if (db->mode != MSIDBOPEN_READONLY )
1026         ret = MSIDBSTATE_WRITE;
1027     msiobj_release( &db->hdr );
1028
1029     return ret;
1030 }
1031
1032 typedef struct _msi_remote_database_impl {
1033     const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1034     MSIHANDLE database;
1035     LONG refs;
1036 } msi_remote_database_impl;
1037
1038 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1039 {
1040     return (msi_remote_database_impl *)iface;
1041 }
1042
1043 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1044                                           REFIID riid,LPVOID *ppobj)
1045 {
1046     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1047         IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1048     {
1049         IUnknown_AddRef( iface );
1050         *ppobj = iface;
1051         return S_OK;
1052     }
1053
1054     return E_NOINTERFACE;
1055 }
1056
1057 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1058 {
1059     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1060
1061     return InterlockedIncrement( &This->refs );
1062 }
1063
1064 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1065 {
1066     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1067     ULONG r;
1068
1069     r = InterlockedDecrement( &This->refs );
1070     if (r == 0)
1071     {
1072         MsiCloseHandle( This->database );
1073         msi_free( This );
1074     }
1075     return r;
1076 }
1077
1078 HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1079                                       BSTR table, MSICONDITION *persistent )
1080 {
1081     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1082     *persistent = MsiDatabaseIsTablePersistentW(This->database, (LPWSTR)table);
1083     return S_OK;
1084 }
1085
1086 HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1087                                    BSTR table, MSIHANDLE *keys )
1088 {
1089     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1090     UINT r = MsiDatabaseGetPrimaryKeysW(This->database, (LPWSTR)table, keys);
1091     return HRESULT_FROM_WIN32(r);
1092 }
1093
1094 HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1095                                           UINT updatecount, MSIHANDLE *suminfo )
1096 {
1097     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1098     UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1099     return HRESULT_FROM_WIN32(r);
1100 }
1101
1102 HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1103                              BSTR query, MSIHANDLE *view )
1104 {
1105     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1106     UINT r = MsiDatabaseOpenViewW(This->database, (LPWSTR)query, view);
1107     return HRESULT_FROM_WIN32(r);
1108 }
1109
1110 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1111 {
1112     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1113     This->database = handle;
1114     return S_OK;
1115 }
1116
1117 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1118 {
1119     mrd_QueryInterface,
1120     mrd_AddRef,
1121     mrd_Release,
1122     mrd_IsTablePersistent,
1123     mrd_GetPrimaryKeys,
1124     mrd_GetSummaryInformation,
1125     mrd_OpenView,
1126     mrd_SetMsiHandle,
1127 };
1128
1129 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1130 {
1131     msi_remote_database_impl *This;
1132
1133     This = msi_alloc( sizeof *This );
1134     if (!This)
1135         return E_OUTOFMEMORY;
1136
1137     This->lpVtbl = &msi_remote_database_vtbl;
1138     This->database = 0;
1139     This->refs = 1;
1140
1141     *ppObj = This;
1142
1143     return S_OK;
1144 }